-1

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?

asked Jan 6, 2014 at 19:22
2
  • 1
    possible duplicate of How to return the response from an AJAX call? Commented Jan 6, 2014 at 19:22
  • It's asynchronous, the console.log executes before the array is populated, as that's the way ajax works. Commented Jan 6, 2014 at 19:27

3 Answers 3

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

answered Jan 6, 2014 at 19:29
Sign up to request clarification or add additional context in comments.

Comments

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.

answered Jan 6, 2014 at 19:53

Comments

-1

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

answered Jan 6, 2014 at 19:24

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.