1

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?

4
  • Did you try data.length? Commented Feb 7, 2013 at 2:35
  • What does it return when you use console.log(data)? Commented Feb 7, 2013 at 2:36
  • possible duplicate of I have a nested data structure / JSON, how can I access a specific value? Commented Feb 7, 2013 at 2:40
  • data is the JSON response, data[0] returns the first item, so... data.length should give you the length Commented Feb 7, 2013 at 3:07

3 Answers 3

2

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.

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

Comments

0
$.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;

                       });

};

Comments

0

In the success callback have you tried;

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

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.