1

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

4
  • That does not seem to be valid JSON. Where does Array come from? Commented Sep 5, 2011 at 20:10
  • @Felix : Added the PHP code that produces the JSON string Commented Sep 5, 2011 at 20:17
  • It seems you are doing another echo somewhere or you just included Array by accident. Make sure it is not in the response. Commented Sep 5, 2011 at 20:20
  • @Felix. Thank you for pointing that out. I had missed out on an echo statement that was adding the 'Array' part. Fixing that solved it all. :D Commented Sep 5, 2011 at 20:27

3 Answers 3

1

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;
}

From: http://www.json.org/js.html

Sign up to request clarification or add additional context in comments.

1 Comment

It doesn't really matter, I just saw that no one shows the code to use from a string to an object, so I showd it in a basic form
0

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);
}

3 Comments

data.length returns 290. So it seems the returned JSON object is being treated as a string.
@ankit, try parsing it then: JSON.parse(data); and operate on the result of this function. The JSON.parse method can be found in json2.js: github.com/douglascrockford/JSON-js
Works like a charm now after removing the stray echo statment suggestion !
0
i=0;
do{
    alert(data[i].categoryName);
    i++;
}
while(i<=data.length);

As described by Darin Dimitrov, but in a While loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.