I\'m wondering why in the code below the i variable still shows \"5\" instead of showing \"1\" then \"2\" the
you can fix this using closures, wrapping the value of i:
for (var i = 0; i < 5; i++) {
(function(val){
$.ajax({
url: '/echo/html/',
method:'post',
data: {
html: 'Ajax data'
},
success: function (resp) {
$('#success').append(val);
}
})
$('#outsideAjax').append(val); // is okay
})(i);
}
Solution using Function#bind():
http://jsfiddle.net/RQncd/1/
for (var i = 0; i < 5; i++) {
$.ajax({
url: '/echo/html/',
method:'post',
data: {
html: 'Ajax data'
},
success: (function (i, resp) {
$('#success').append(i);
}).bind(null, i)
});
$('#outsideAjax').append(i);
}
This is due to Closures in JavaScript. Here's the fix -
for (var i = 0; i < 5; i++) {
(function(i){
$.ajax({
url: '/echo/html/',
method:'post',
data: {
html: 'Ajax data'
},
success: function (resp) {
$('#success').append(i)
}
})
})(i);
$('#outsideAjax').append(i);
}
fiddle Demo
var i = 0;
function ajax_call() {
$.ajax({
url: '/echo/html/',
method: 'post',
data: {
html: 'Ajax data'
},
success: function (resp) {
$('#success').append(i++);
if (i < 5) {
ajax_call();
}
}
});
$('#outsideAjax').append(i);
};
ajax_call();