jQuery. obtain var from ajax in cycle - javascript

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);
}
});
}

Related

How to update variable in parent function inside AJAX WITHOUT ASYNC FALSE

AJAX is async by default and as of jquery 1.8, setting async: false is deprecated. I do not wish to break asynchronous property of AJAX anyway. Most of answers I found on here say to set async false. So what is a better way to do it? I would like to update count after all the loops are done.
$.ajax({
url: "...",
success: function (objects) {
var count = 0;
for (var i = 0; i < objects.length; i++) {
logObject(object[i], count); // update count in every loop
}
console.log(count); // ALWAYS 0
}
});
function logObject(object, count) {
$.ajax({
url: "...",
success: function (result) {
console.log(object.item); // works fine
count+=result.count; // count increases everytime unless result.count is 0
}
});
}
One way would be to increment a counter on start and reduce when done, like this:
var activeAjaxConnections = 0;
.ajax({
beforeSend: function(xhr) {
activeAjaxConnections++;
},
success: function(resp) {
activeAjaxConnections--;
if (activeAjaxConnections === 0) {
// done.....
}
},
error: function(xhr, errDesc, exception) {
activeAjaxConnections--;
}
});
Or - more global - you play around with: ajaxComplete
First of all you pass "count" parameter to function and update it inside this function. It never works because "count" is a primitive type, is integer, and inside your function "logObject" you will work with the copy of "count" is passed by value.
$.ajax({
url: "...",
success: function (objects) {
var count = 0;
for (var i = 0; i < objects.length; i++) {
logObject(object[i]).success(function(result){
count += result.count;
if((i + 1) === objects.length){
//Here you finished the loop
console.log(count);
}
}); // update count in every loop
}
}
});
function logObject(object) {
return $.ajax({
url: "..."
});
}

for loop is not calling restful api

Here is my code neat and clean
as you can see i have make a for loop and passing a[i] variable to the api
now what is happeing is for loop is is not hitting the api and going back to the loop. any solution?
var a = ['a1','a2','a3','a4','a5','a6','a7','a8','a9','a10','a11','a12','a13','a14','a15','a16','a17','a18','a19','a20','a21','a22','a23','a24','a25','a26','a27','a28','a29','a30','a31','a32','a33','a34','a35','a36', 'a37']
console.log(a)
for(var i = 0; i <= a.length; i++){
$http({
url: '/MyApp/getIt?urlofpage=https://www.example.com/alpha/'+a[i]+'.html',
method: "POST",
}).success(function(response){
console.log(a[i]);
console.log(response);
});
}
It looks like you are trying to use jQuery ajax to get the API called.
If this is the case, you should use $.post or $.ajax:
var a = ['a1','a2','a3','a4', ...];
console.log(a);
for(var i = 0; i <= a.length; i++){
$.ajax({
url: '/MyApp/getIt?urlofpage=https://www.example.com/alpha/'+a[i]+'.html',
method: "POST",
success: function(response) {
console.log(a[i]);
console.log(response);
}
});
}
Otherwise, please share the $http function.
You can't use the for loop for the database call since it is asynchronous.Have a look on following code.
var a = ['a1','a2','a3','a4', ...];
var i=0;
checkArrayLength();
function checkArrayLength(){
if(i<a.length){
makeRequest(a[i]);
}
}
function makeRequest(param1){
$.ajax({
url: '/MyApp/getIt?urlofpage=https://www.example.com/alpha/'+param1+'.html',
method: "POST",
success: function(response) {
console.log(a[i]);
i=i+1;
console.log(response);
checkArrayLength();
},
error:function(response) {
console.log(a[i]);
i=i+1;
console.log(response);
checkArrayLength();
}
});
}

Proper way to loop jQuery ajax and pass arguments

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)

ajax in a loop without correct value

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);
}
}
});
}

Ajax success with external variable

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);
}

Categories