I am using each()
on the result of my AJAX request, my code is as below:
<script type="text/javascript">
function my_function() {
str = [];
$i = 0;
$(".div_class").each(function() {
var id = $(this).attr('id');
$.ajax({
type: 'post',
url: 'my_url',
cache: false,
data: {id: id},
success: function(data) {
alert(data.result); // alert 1
str.push({$i : data.result});
}
});
$i++;
});
alert(JSON.stringify(str)); // alert 2
}
</script>
I am getting result in alert(data.result)
.
The problem is the alert 2 alert(JSON.stringify(str));
is appearing first and with an empty value.
Does any one know what the problem is?
The issue is because the AJAX request is asynchronous. This means script execution continues while waiting for the return value - which is why you see alert 2
before alert 1
.
When working with async methods, all code which depends on the request should be placed in the callback function. In other words, alert 2
has to be placed inside the success
handler function.
Since your ajax call is an async one, the statement alert(JSON.stringify(str));
will be executed right after the ajax call and it will not wait for the request to be finished. If you want to stringify it, then do it in success
or done
methods
The problem is the asynchronous nature of ajax requests
You can use $.when()
function my_function() {
var requests = [];
var str = [];
$(".div_class").each(function () {
var id = $(this).attr('id');
var req = $.ajax({
type: 'post',
url: 'my_url',
cache: false,
data: {
id: id
},
success: function (data) {
alert(data.result); // alert 1
str.push({
$i: data.result
});
}
});
requests.push(req);
});
$.when.apply($, requests).done(function () {
alert(JSON.stringify(str)); // alert 2
})
}
If you want to maintian the order of items then you can
function my_function() {
var requests = $(".div_class").map(function () {
var id = this.id;
return $.ajax({
type: 'post',
url: 'my_url',
cache: false,
data: {
id: id
},
success: function (data) {
alert(data.result); // alert 1
}
});
}).get();
$.when.apply($, requests).done(function () {
var str = $.map(arguments, function (arr) {
return arr[0].result;
})
alert(JSON.stringify(str)); // alert 2
})
}
Demo: Fiddle