0

I have city object in my project. I want to create a jquery array with some city objects. I can take city list from .ashx file and create single city objects. But I couldn't push them to an array. Here is my code:

 var postDataCity = { funcName: "GetCities" };

        var cities = [];
        var city = {};

        $.ajax({
            type: "POST",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            dataType: "json",
            url: "KurumInformation.ashx",
            data: postDataCity,
            async: true,
            success: function (msg) {
                $.each(msg, function (i, v) {
                    city.M_CityId = this.M_CityId ;
                    city.M_CityName= this.M_CityName;
                    cities.push(city);
                });
            },
            error: function (d) {
                alert('error :' + d);
            },
        });

        console.log(cities);

After this I check cities but there is an error I think because I can't see cities in console. Where is my mistake?

cagin
  • 5,772
  • 14
  • 74
  • 130
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – adeneo Jan 06 '14 at 19:22
  • It's **asynchronous**, the console.log executes before the array is populated, as that's the way ajax works. – adeneo Jan 06 '14 at 19:27

3 Answers3

2

Your code is almost fine, you have to declare the city inside the loop.

Also you have just to move the console.log after the pushing to see the results:

success: function (msg) {
    $.each(msg, function (i, v) {
        var city = {};   //Move declaration here
        city.M_CityId = this.M_CityId ;
        city.M_CityName= this.M_CityName;
        cities.push(city);
    });
    console.log(cities);   //Move it here
},

If you declare it outside, you'll be adding to the array the same city reference each time.

Also, as the ajax call is asynchronous, your old console.log executed before the ajax call finished, that's why you saw empty results.

Cheers

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
0
$.each(msg, function (i, v) {
       city.M_CityId = v.M_CityId ;
       city.M_CityName= v.M_CityName;
       cities.push(city);
});

It will work fine.

Hannan Hossain
  • 740
  • 1
  • 12
  • 23
-1

You display the variable before the callback of the AJAX call is made. You should have your console.log() inside the callback.

jillro
  • 4,456
  • 2
  • 20
  • 26