Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a PHP script which creates a JSON array called 'cities'.

I can retrieve data from that using the following JQuery:

$.ajax({
  dataType: "json",
  url: "mysql.php",
  success: function(data){

    console.log(data[0]);//Returns first item in cities array

};

But I am unsure how to loop through the data retrieved and enter it into a JavaScript array.

I dont really have anyway of initialising a count, such as:

var counter = cities.length;

it doesnt seem to recognised 'cities; is the name of the retrieved JSON array.

Am I missing something in my ajax script?

share|improve this question
Did you try data.length? – Floyd Pink Feb 7 at 2:35
What does it return when you use console.log(data)? – Dom Feb 7 at 2:36
data is the JSON response, data[0] returns the first item, so... data.length should give you the length – Christophe Feb 7 at 3:07

3 Answers

up vote 0 down vote accepted
$.ajax({
dataType: "json",
url: "mysql.php",
success: function(data){

$.each(data.info , function() { //refer to the Json object to address the actual names

    var cityname = this.cityname;

                       });

};
share|improve this answer

If what you get back is a JSON array, you could convert that into a JS array using the JSON.parse method.

$.ajax({
  dataType: "json",
  url: "mysql.php",
  success: function(data){
    var cities = JSON.parse(data);
    console.log(cities.length);
};

If it's just an array of strings, you wouldn't even need to do a JSON.parse, because JSON is nothing but a stringified representation of JavaScript object notation. But JSON.parse would help convert a JSON to its corresponding JavaScript object notation for any valid JS objects.

share|improve this answer

In the success callback have you tried;

success: function ( data ) {
    for ( var index = 0; index < data.length; index++ ) {
        console.log( data[ index ] );
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.