I'm wondering why in the code below the i variable still shows "5" instead of showing "1" then "2" then "3" and so on ? Must be a scope issue but I don't really get it as I changed the scope of i variable in global and dom scope and still getting the same problem.
When I alert i outside the ajax function, it works well.
for (var i = 0; i < 5; i++) {
$.ajax({
url: '/echo/html/',
method:'post',
data: {
html: 'Ajax data'
},
success: function (resp) {
$('#success').append(i) // always 5
}
})
$('#outsideAjax').append(i); // is okay
}
Here is the fiddle
EDIT :
I went for #Tushar Gupta solution as it best suits my needs but I get another issue, the iteration won't work if I set this option : processData: false
See the fiddle
Why is this not working ?
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);
}
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);
}
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();
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);
}
Related
From the function django I return JSON to JS
paymentparking = paidparking.objects.filter(expirationdate__range=(startdate, enddate)).values('expirationdate','price')
return JsonResponse({'result': list(paymentparking)})
Here I need to get all the expirationdate values. How can this be done and how can the cycle be organized?
$.ajax({
type: "POST",
url: "statistics",
data: {
'startdate': finalDateStrStart,'enddate': finalDateStrEnd,
},
dataType: "json",
cache: false,
success:function (data) {
for (let i = 0; i < 100; i++)
{
console.log(data.result[i].expirationdate)
}
}
});
You could maybe do something like this:
success: function (data) {
if(data.result) {
for (let i = 0; i < data.result.length; i++) {
console.log(data.result[i].expirationdate)
}
}
}
Use Array.map() to iterate over elements and return an array of expirationdate.
success: function (data) {
data?.result && data.result.map(obj => console.log(obj.expirationdate));
}
I see a lot of solutions to queue ajax requests but I am trying to understand how to implement one for this case. Should it be a push and shift queue?:
var urlList = ['urlA', 'urlB', 'urlC', ...];
function initSession() {
for (var i = 0; i < urlList.length; i++) {
getResponse(urlList[i]); // this is what I would like to queue.
}
}
function getResponse(theURL) {
steps.shuffleLetters({
"text": messages[mesInd]
});
$.ajax({
method: 'GET',
url: theURL,
dataType: 'text',
success: function(data) {
setTimeout(function() {
steps.shuffleLetters({
"text": data
});
}, 1000);
mesInd = mesInd + 1;
},
error: function(data) {
setTimeout(function() {
steps.shuffleLetters({
"text": "Click Again!"
});
}, 1000);
mesInd = 0;
}
});
}
You can do that by removing the for loop and call the next url after the success of the current request
Check the code below:
var urlList = ['urlA','urlB','urlC',...];
var length = urlList.length;
var currentRequest = 0;
getResponse(urlList[currentRequest]);
function getResponse(theURL){
steps.shuffleLetters({"text": messages[mesInd]});
$.ajax({
method: 'GET',
url: theURL,
dataType: 'text',
success: function (data) {
setTimeout(function(){steps.shuffleLetters({"text": data});}, 1000);
//Here you will call the next request
currentRequest +=1;
if(currentRequest < length)
{
getResponse(urlList[currentRequest]);
}
mesInd = mesInd+1;
},
error: function (data) {
setTimeout(function(){steps.shuffleLetters({"text": "Click Again!"});}, 1000);
mesInd = 0;
}
});
}
I'm doing a GET request using $.ajax():
jQuery(function ($) {
$('#acsess').on('click', function () {
$.ajax({
url: 'http://f4c0c1f3aa9a506c69b3b6642864b3590fb8f76f#504080.com/api/v1/services/categories',
method: 'GET',
beforeSend: function(req) {
req.setRequestHeader('Authorization', "f4c0c1f3aa9a506c69b3b6642864b3590fb8f76f");
},
success: function(data) {
console.log(data);
jQuery.each(data, function (index, value) {
// need to create divs with *icon and *title from data
})
},
error: function(error) {
alert("error");
}
})
});
});
I got this in my console:
And I can't retrieve icon link and title text. Please help.
You can access the data (which seems to be an array) by data[index].icon and data[index].title.
If you need to access all the items, I recommend a simple loop:
success: function(data) {
for (var i = 0; i++; i < data.length) {
data[i].icon // it's here, what to do is up to you
}
}
it helps me to resolve problem
success: function(data) {
var ololo = data.data;
for (let i = 0; i < ololo.length; i++) {console.log(ololo[i].title);}
}
i'm trying to send ajax call to php file which return 1000 record at a time in json encoded format which i am appending in table. everything working fine but it takes alot for time which result in hanging of page. below is my js code.
$(window).load(function() {
for (i = 0; i < 31; i++)
{
$.ajax({
type: "GET",
url: "filters.php",
data: {limit: 1000, start_from: (i * 1000)},
success: function(response) {
var array = JSON.parse(response);
Object.keys(array).forEach(function(key) {
oTable.fnAddData([
array[key][1],
array[key][2],
array[key][3],
array[key][4],
array[key][5],
array[key][6],
array[key][7],
array[key][8],
array[key][9],
array[key][10],
array[key][11],
array[key][12],
array[key][13],
array[key][14],
array[key]['link']
]);
});
},
datatype: 'json'
});
}
});
Try this:
$(window).load(function() {
for (i = 0; i < 31; i++)
{
setTimeout(500,function(){
$.ajax({
type: "GET",
url: "filters.php",
data: {limit: 1000, start_from: (i * 1000)},
success: function(response) {
var array = JSON.parse(response);
Object.keys(array).forEach(function(key) {
oTable.fnAddData([
array[key][1],
array[key][2],
array[key][3],
array[key][4],
array[key][5],
array[key][6],
array[key][7],
array[key][8],
array[key][9],
array[key][10],
array[key][11],
array[key][12],
array[key][13],
array[key][14],
array[key]['link']
]);
});
},
datatype: 'json'
});
});
}
});
i have:
function load_data(data) {
var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
myMask.show();
$.ajax({
url: '/dostup/data_json.php',
method: 'GET',
async: true,
data: {
epsg: data
},
dataType: 'json',
error: function(jqXHR, status, error) {
console.log('ошибка получения данных: '+data);
},
success: function(data2) {
window[data] = data2;
window[data+"_layer"].clearLayers();
window[data+"_layer"].addData(eval(data));
myMask.hide();
}
});
}
And myMask hidden before window[data] loading on site(client).
I try set async: false and myMask not show(i try and beforeSend too).
P.S. i have:
function search_handler(val) {
search_list=[];
for (var t = 0; t < layer_array.length; t++) { //>
if (window[layer_array[t]] != undefined && !eval(layer_array[t]).features) load_data(layer_array[t]);
if (window[layer_array[t]] != undefined && eval(layer_array[t]).features) {
for (var i = 0; i < eval(layer_array[t]).features.length; i++) { //>
search_list.push(eval(layer_array[t]).features[i]);
}
}
}
....more script
}
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
You need to use ajaxStart and ajaxStop like that:
$(document)
.ajaxStart(function () {
myMask.show();
})
.ajaxStop(function () {
myMask.hide();
});