cagin
cagin

Reputation: 5920

How to create a jquery object array

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?

Upvotes: -1

Views: 91

Answers (3)

Hannan Hossain
Hannan Hossain

Reputation: 740

$.each(msg, function (i, v) {
       city.M_CityId = v.M_CityId ;
       city.M_CityName= v.M_CityName;
       cities.push(city);
});

It will work fine.

Upvotes: 0

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

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

Upvotes: 2

jillro
jillro

Reputation: 4559

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

Upvotes: -1

Related Questions