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?
-
1possible duplicate of How to return the response from an AJAX call?adeneo– adeneo2014年01月06日 19:22:50 +00:00Commented 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.adeneo– adeneo2014年01月06日 19:27:51 +00:00Commented Jan 6, 2014 at 19:27
3 Answers 3
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
Comments
$.each(msg, function (i, v) {
city.M_CityId = v.M_CityId ;
city.M_CityName= v.M_CityName;
cities.push(city);
});
It will work fine.
Comments
You display the variable before the callback of the AJAX call is made. You should have your console.log() inside the callback.