I got a problem with ajax in a loop.
I found the loop variable "i" did not increase.
Supposed there were 3 items in the array1, the script would alert 4,4,4
But not 1,2,3 as I expected.
Could someone give me a hint?
Many thanks.
var i;
for(i=1;i<=array1.length;i++){
tmp=array1[i-1];
$.ajax
({
type: "POST",
url: "ajax_feedback.php",
data: {id : tmp.id},
success: function(msg)
{
alert(i);
}
});
}
So the solution for this problem is :
var i;
for(i=1;i<=array1.length;i++){
tmp=array1[i-1];
ajaxCall(i);
}
function ajaxCall(i){
$.ajax
({
type: "POST",
url: "ajax_feedback.php",
data: {id : tmp.id},
success: function(msg)
{
alert(i);
}
});
}
Whenever you are making ajax call in loop.Never try to call it directly.It is because ajax call is asynchronous and till the time success code come back from server,i value get incremented and because of which,it is showing 4,4,4 as output in alerts.
Try:
var len = array1.length;
show(0);
function show(i){
var tmp=array1[i-1];
$.ajax({
type: "POST",
url: "ajax_feedback.php",
data: {id : tmp.id},
error:function(){
if(i < len){
show(i+1);
}
},
success: function(msg){
alert(i);
if(i < len){
show(i+1);
}
}
});
}
Related
I'm relatively new to javascript, and I have a restful api I'm connecting to that returns me a json string, which I can parse properly like so:
$.ajax({ url: './php/bandwidth.php',
data: { prop_id : "1" },
type: 'post',
success: function(output) {
var json = $.parseJSON(output);
for( var i = 0 ; i < json.response.length; i++ ){
times.push (json.response[i].time);
}
}
});
Inside of the success callback the variables in the array exist. I also have times array instantiated outside the ajax call function. But outside of the ajax call the array is empty. I'm sure it's a scoping issue. Can anyone give me a way to get the data from inside the array? Does the construct $.ajax({url:... , data:... , success: function(){}}); returns callback return value?
$.ajax({ url: './php/bandwidth.php',
data: { prop_id : "1" },
type: 'post',
dataType: 'json',
success: function(output) {
times = [];
for( var i = 0 ; i < output.response.length; i++ ){
times.push (output.response[i].time);
}
},
complete: function(){
if(times.length > 0){ console.log(times); } else { console.log("times empty"); }
}
});
I want to solve once for all the problem of looping ajax request and passing 'index' into it (the problem below):
for (var index = 0; index < 4; index++) {
$.ajax({
url: 'http://graph.facebook.com/',
dataType: 'jsonp',
success: function(json) {
console.log(json[index]);
}
});
}
in this code within every 'success' callback 'index' will be 3. But I want to invoke callback with 0, 1, 2, 3. Many people are placing ajax request within a closure:
for (var index = 0; index < 4; index++) {
(function(index){$.ajax({
url: 'http://graph.facebook.com/',
dataType: 'jsonp',
success: function(json) {
console.log(json[index]);
}
});
})(index);
}
what in my opinion is a huge mistake - what if the request won't be there at the time? Than 'json' variable will be 'undefined'.
Does any of You guys have some proper way to solve this issue?
Actually the JSON will not be undefined.
If you would break the following code apart it would become more clear:
So instead of this:
for (var index = 0; index < 4; index++) {
(function(index){$.ajax({
url: 'http://graph.facebook.com/',
dataType: 'jsonp',
success: function(json) {
console.log(json[index]);
}
});
})(index);
}
...you can also write it like this:
function myFunction(index) {
$.ajax({
url: 'http://graph.facebook.com/',
dataType: 'jsonp',
success: function(json) {
console.log(json[index]);
}
});
}
// and call it like this
for (var index = 0; index < 4; index++) {
myFunction(index);
}
As you might already see, how are any of those two variables going to change by another call while they are defined inside the function?
(On a side note: I think it actually looks cleaner this way)
How can I use an external variable i inside the Ajax success?
For example:
for (i = 0; i < 3; ++i) {
$.ajax({
type: "POST",
data: "user=132",
url: "../php/order_ajax.php",
success: function(data){
$('.obj' + i).html(data);
}
});
}
you should close it in for example anonymous function. It is because ajax call is asynchronous and I bet you that loop is finished even before the first ajax call is done which means that "i" will be 4 by that time.
var user = 1;
for (i = 0; i < 3; ++i) {
(function(i){
$.ajax({
type: "POST",
data: "user="+ user,
url: "../php/order_ajax.php",
success: function(data){
$('.obj' + i).html(data);
}
});
})(i);
}
Here is what bothering me. My code is running on document.ready. I need the request to be asynchronous, meaning async: true
for (var i = 0; i < totalGraphs; i++) {
var kpiId = kpiIds[i];
jQuery.ajax({
type: 'POST',
url: graphUrl,
data: "kpiId="+kpiId+"&divId="+(i+1),
async: true, //if false things are working fine
cache:false,
success: function(response){
document.getDocumentById("graph" + (i + 1)).innerHTML("hello");
},
error:function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
This request does not put hello in my graphX divs, but whenever i put async: false things are working fine. I really need the request to be asynchronous.
Thanks in advance for any help.
Try this...
for (var i = 0; i < totalGraphs; i++){
(function ajaxCall(index) {
var kpiId = kpiIds[index];
jQuery.ajax({
type: "POST",
url: graphUrl,
data: {
kpiId : kpiId,
divId : index + 1
},
async: true, //if false things are working fine
cache: false,
success: function(response) {
document.getDocumentById("graph" + (index + 1)).innerHTML("hello");
},
error: function(XMLHttpRequest,textStatus,errorThrown) {}
});
})(i);
}
I've wrapped the ajax call in an anonymous function so that the value of i will never change, relative to the ajax call.
I'm guessing the i count is getting mixed up in your loop when success is returned. success will return after the loop has run through and thus this will give an unexpected result.
Can you return the i value that went sent in data in your response then use this in your getDocumentById method? I'm guessing this would fix your issue.
New code to try:
for(var i=0;i<totalGraphs;i++){
jQuery.ajax({
type: 'POST',
url: graphUrl,
data: { kpiId: kpiIds[i], divId: (i+1) },
async: true, //if false things are working fine
cache:false,
success: function(response){
document.getDocumentById("graph" + response.count).innerHTML("hello");
},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
}
First of all, you are running an ajax call inside a loop. This will be okay if you've turned off the async. But since you've turned on the async, the loop doesn't wait for the ajax to finish its work.
The best thing to do would be to get the values to a global variable using the inner loop ajax and then use the variable to draw the graph later.
for (var i = 0; i < 3; i++){
$.ajax({
url: "ajax.php",
success: function(data){
alert(i);
}
});
}
I need a solution to get alerts with "0", "1" and "2". Аt this time of course I see 3 alerts with "3".
You need to put a closure around your $.ajax() call.
for (var i = 0; i < 3; i++){
(function (loop_var) {
$.ajax({
url: "ajax.php",
success: function(data){
alert(loop_var);
}
});
})(i);
}
Currently it is outputting 3 as my the time the Ajax returns the value of i is indeed 3.
Use an anonymous function wrapper around the code to create a closure that will keep the value until the asynchronous response arrives:
for (var i = 0; i < 3; i++){
(function(i){
$.ajax({
url: "ajax.php",
success: function(data){
alert(i);
}
});
})(i);
}
Pass the i value to the ajax.php page as a parameter.
The ajax.php page has to return i to the calling page. So let the ajax.php page return i.
You can use json objects or a trivial pipe-separated string to store returning values from ajax.php.
for (var i = 0; i < 3; i++){
$.ajax({
data: {par: i},
url: "ajax.php",
success: function(data){
//data is a pipe-separated string
var cnt = data.split("|")[0];
alert(cnt);
}
});
}