MeltingDog
MeltingDog

Reputation: 15490

JQuery: Store JSON results in a JavaScript array?

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?

Upvotes: 1

Views: 7778

Answers (3)

Solorzano Jose
Solorzano Jose

Reputation: 632

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

                       });

};

Upvotes: 0

whitneyit
whitneyit

Reputation: 1226

In the success callback have you tried;

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

Upvotes: 0

Hari Pachuveetil
Hari Pachuveetil

Reputation: 10384

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.

Upvotes: 2

Related Questions