Reputation: 179
function getWriters(cat, lev, id)
{
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("writer").innerHTML = xmlhttp.responseText;
var writer = eval(xmlhttp.responseText);
document.write(writer)
}
}
xmlhttp.open("GET", "order.php?op=2&id=0&cat=" + cat + "&lev=" + lev, true);
xmlhttp.send();
}
xmlhttp.responseText returns
Array ( [0] => Array ( [name] => Unassigned [user_id] => 2 [writing_level] => [writing_category] => ) [1] => Array ( [name] => arsalan [user_id] => 3 [writing_level] => [writing_category] => ) [2] => Array ( [name] => Shazia [user_id] => 4 [writing_level] => [writing_category] => ) [3] => Array ( [name] => janea [user_id] => 5 [writing_level] => [writing_category] => ) [4] => Array ( [name] => s [user_id] => 6 [writing_level] => [writing_category] => ) [5] => Array ( [name] => iuiui [user_id] => 8 [writing_level] => [writing_category] => ) [6] => Array ( [name] => demo [user_id] => 9 [writing_level] => [writing_category] => ) [7] => Array ( [name] => wewe [user_id] => 10 [writing_level] => [writing_category] => ) [8] => Array ( [name] => Muhammad Zoyeb [user_id] => 11 [writing_level] => [writing_category] => ) [9] => Array ( [name] => Atif Rauf Alvi [user_id] => 12 [writing_level] => [writing_category] => ) [10] => Array ( [name] => demo-1 [user_id] => 13 [writing_level] => [writing_category] => ) [11] => Array ( [name] => ffff** [user_id] => 14 [writing_level] => High School,Masters [writing_category] => Literature and Language,Social Sciences ) )
i am getting syntax error at document.write(writer); if i remove eval() there is no syntax error.
Can anyone explain how to fix this or some other way to convert the string returned to array.
Thanks
Upvotes: 1
Views: 1373
Reputation: 344605
The string being returned from the server isn't valid JSON or JavaScript syntax, so you can't pass it to eval()
. It looks like you're using PHP's print_r
function on the array at the server — you need to use json_encode
(PHP >5.2):
echo json_encode($myArray);
Then you can parse it locally with JSON.parse
(recommended) or eval
.
Upvotes: 3
Reputation: 16084
You're returning the PHP "representation" of an array and by evaluating this string you fall into the syntax error.
Try this:
To split a string use:
var response = xmlhttp.responseText;
var responseArray = response.split(",");
Upvotes: 0
Reputation: 385204
It looks like your JSON response is the stringifed version of a PHP array. Why not return JSON from your PHP, then Javascript picks up the array natively.
Upvotes: 0