I am getting a perfectly created JSON object from server response.
For example:
{
"users": [
{
"userId": 20410,
"firstName": "Viral",
"lastName": "Shah",
"loginId": "[email protected]",
"userRole": 3
},
{
"userId": 400881,
"firstName": "Viral",
"lastName": "Shah",
"loginId": "[email protected]",
"userRole": 0
},
{
"userId": 425622,
"firstName": "Viral",
"lastName": "Shah",
"loginId": "[email protected]",
"userRole": 0
}
]
}
I am using this in JavaScript using AJAX like below:
var jsonobj2 = null;
var respObj = getSearchedWPUsers(firstname, lastname, loginid); //return json response
var len = respObj.length;
jsonobj2 = eval('(' + respObj + ')');
var tablehtml = "<table><tr><td><b>First Name</td><td><b>Last Name</td><td><b>Login Id</td><td><b>Editing Rights</td></tr><tr></tr>";
for (i = 0; i < len; i++) {
tablehtml = tablehtml + "<tr>";
//--------------
tablehtml = tablehtml + "<td>";
tablehtml = tablehtml + jsonobj2.users[i].firstName;
tablehtml = tablehtml + "</td>";
//--------------
tablehtml = tablehtml + "<td>";
tablehtml = tablehtml + jsonobj2.users[i].lastName;
tablehtml = tablehtml + "</td>";
//--------------
tablehtml = tablehtml + "<td>";
tablehtml = tablehtml + jsonobj2.users[i].loginId;
tablehtml = tablehtml + "</td>";
//--------------
tablehtml = tablehtml + "<td><b>";
var role = jsonobj2.users[i].userRole;
if (role == 1 || role == 2 || role == 3) tablehtml = tablehtml + "<a href ='javascript:removeXML(" + jsonobj2.users[i].userId + ")'><u><font color='red'>Revoke access</font></a> ";
else tablehtml = tablehtml + "<a href ='javascript:generateXML(" + jsonobj2.users[i].userId + ")'><u><font color='blue'>Assign access</font></a> ";
tablehtml = tablehtml + "</td>";
tablehtml = tablehtml + "</tr>";
}
tablehtml = tablehtml + "</table>";
document.getElementById("TableHolder").innerHTML = tablehtml;
//--------------------------
It throws errors like below
TypeError: jsonobj2.users[i] is undefined
[Break On This Error]
tablehtml = tablehtml + jsonobj2.users[i].firstName;
tried with JSON.parse(serverresponse);
-- nothing happened
Please help
respObj
is what you think it is? It seems strange to return a value from a function making an Ajax call. Please show us what it contains. – Felix Kling Jan 11 at 14:38respObj
contains something? You might need to doasync: false
ajax in order to return something from ajax call. Because ajax is asynchronous. – Aamir Adnan Jan 11 at 14:38