I am new to Ajax and I am attempting to use Ajax while using a for loop. After the Ajax call I am running a function that uses the variables created in the Ajax call. The function only executes two times. I think that the Ajax call may not have enough time to make the call before the loop starts over. Is there a way to confirm the Ajax call before running the function printWithAjax()? I do not want the printWithAjax() function to execute until the Ajax call is complete. Any help will be greatly appreciated.
var id; var vname; function ajaxCall(){ for(var q = 1; q<=10; q++){ $.ajax({ url: 'api.php', data: 'id1='+q+'', dataType: 'json', async:false, success: function(data) { id = data[0]; vname = data[1]; } }); printWithAjax(); }//end of the for statement }//end of ajax call function
You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });
The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.
success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine. However, . complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - . complete() will still get called.
Try this code:
var id; var vname; function ajaxCall(){ for(var q = 1; q<=10; q++){ $.ajax({ url: 'api.php', data: 'id1='+q+'', dataType: 'json', async:false, success: function(data) { id = data[0]; vname = data[1]; }, complete: function (data) { printWithAjax(); } }); }//end of the for statement }//end of ajax call function
The "complete" function executes only after the "success" of ajax. So try to call the printWithAjax() on "complete". This should work for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With