I am new to JSON and AJAX and was hoping someone could help me out here.
Using an AJAX request to a PHP script, I get some data from SQL database -> encoded as JSON string and sent it back to the calling javascript.
This is the data i get back
Array[{"categoryName":"Apartments For Rent"},{"categoryName":"Apartments For Sale"},{"categoryName":"Room For Rent (Shared)"},{"categoryName":"Paying Guest"},{"categoryName":"Office\/Shop\/Commercial Space"},{"categoryName":"Land"},{"categoryName":"Parking Spots"},{"categoryName":"Other"}]
How can I get the individual 'CategoryName' values from this (in a while loop)?
EDIT : PHP CODE THAT SENDS THE JSON DATA
$arr = array();
while($row = mysql_fetch_array($temp,MYSQL_ASSOC))
{
$arr[]=$row;
}
echo json_encode($arr);
Thank you for the help
Ankit
You could loop through the array and access individual elements by their index:
for (var i = 0; i < data.length; i++) {
alert(data[i].categoryName);
}
Use eval() to decode it to a javascript object and then loop trough it, but you'll have to remove the "Array" at the start on the php side or using javascript.
var jsonStr = '[{"categoryName":"Apartments For Rent"},{"categoryName":"Apartments For Sale"}]';
jsonObj = eval("("+jsonStr+")");
for(var i in jsonObj){
categoryName = jsonObj[i].categoryName;
}
i=0;
do{
alert(data[i].categoryName);
i++;
}
while(i<=data.length);
As described by Darin Dimitrov, but in a While loop.