Ajax call in Ajax Call, First One Always completes? [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have an ajax call, that based on the return, calls another ajax call by effecting its url parameter, the url being modified by the return of the first. These two calls are related, because the first feeds the url parameter of the second, and its output is appended to a global variable which is used to generate a final set of HTML, subsequently appended in the first call. As a simplified example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var masterHtml = '';
$.ajax({
url: "http://thisisanexample/items",
type: "GET",
asynch: false,
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
successHandler(data);
},
error: function (data) {
}
});
function successHandler(data) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var someHtml = results[i]["someHtml"];
masterHtml = masterHtml + someHtml;
var nextThingUrl = results[i]["nextThingUrl"];
// now go get the other HTML, and append it to the masterHtml,
//this is a series of child elements to the someHtml variable above
$.ajax({
url: "http://thisisanexample/+ " + nextThingUrl,
type: "GET",
asynch: false,
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
successHandlerChildren(data);
},
error: function (data) {
}
});
jQuery('#magictime').append(masterHtml);
}
}
function successHandlerChildren(data) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var someMoreHtml = results[i]["someMoreHtml"];
masterHtml = masterHtml + someMoreHtml;
}
}
My problem is the first ajax call always completes all the way before the second call is issued so I get the first set of HTML, while the second call provides some HTML I need. This messes up the order of operations. What am I missing? TIA!!!

The option for async is spelled wrong, correct is:
async: false

Looks like you're appending your data too early. Move jQuery('#magictime').append(masterHtml); to function successHandlerChildren(data)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var masterHtml = '';
$.ajax({
url: "http://thisisanexample/items",
type: "GET",
asynch: false,
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
successHandler(data);
},
error: function (data) {
}
});
function successHandler(data) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var someHtml = results[i]["someHtml"];
masterHtml = masterHtml + someHtml;
var nextThingUrl = results[i]["nextThingUrl"];
// now go get the other HTML, and append it to the masterHtml,
//this is a series of child elements to the someHtml variable above
$.ajax({
url: "http://thisisanexample/+ " + nextThingUrl,
type: "GET",
asynch: false,
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
successHandlerChildren(data);
},
error: function (data) {
}
});
}
}
function successHandlerChildren(data) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var someMoreHtml = results[i]["someMoreHtml"];
masterHtml = masterHtml + someMoreHtml;
}
jQuery('#magictime').append(masterHtml);
}

Related

AJAX running in a for loop - Callback function after for loop

So I have a function that executes an ajax call in a for loop. I need to callback another function when the entire for loop is done. Since the ajax calls are running asynchronously, I'm not able to call the next function once the for loop is done.
Here's my code:
for(let i=0; i< industryArray.length; i++){
$.ajax({
url: myurl + "_api/web/lists/GetByTitle('library')/items",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
RejectedSalesCount += data.d.results.length;
},
error: function (data) {
}
})
}
// Need to call myfunction() here
myfunction() is being called even before the ajax calls are executed. Thanks!
Set ajax asyc state false then it will work
this is a sample example to set ajax asyc false
$.ajax({
url : "/submit/checkuser/",
type : "get",
async: false,
success : function(userStatus) {
if (userStatus == 'Disabled') { // check if user if disabled
} else if (userStatus == 'Deleted') { // check if user if deleted
} else {
};
},
error: function() {
connectionError();
}
});
Right now it wait for the function to get executed and moved to the next line
var pendingRequests=0;
for(let i=0; i< industryArray.length; i++){
if (condition) {
pendingRequests++;
$.ajax({
url: myurl + "_api/web/lists/GetByTitle('library')/items",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
RejectedSalesCount += data.d.results.length;
pendingRequests--;
if(pendingRequests===0) {
otherFunction()
}
},
error: function (data) {
doSomethingWithError(data)
}
})
}
}

Ajax Call not storing data in Array

The following code is not storing values in the Array
var checkListIdForEmail= new Array();
var checkListNameforEmail;
function getCheckListIdAndName() {
$.ajax({
type: "GET",
url: 'URL/' + 12464,
dataType: 'json',
contentType: false,
processData: false,
success: function (result) {
for (var i=0; i< result.length;i++) {
$('#checkListIdForEmail').val(result.checklistDetailId[i]);
}
// alert("Success");
},
error: function (error) {
alert("Errror while getting header values");
}
});
}
Can anyone please let me know what needs to store all data in an array..
Thank You
I would suggest on your success callback, do this instead.
success: function (result) {
checkListIdForEmail = result;
},
since result is already an array
Maybe this is what you want to store to the checkListIdForEmail array:
for (var i=0; i< result.length;i++) {
checkListIdForEmail[i] = result[i].checklistDetailId;
}
$('#checkListIdForEmail').val(checkListIdForEmail);

Looping through two JSON arrays Ajax

I'm trying to get data from a Json file using the id from a previous previous ajax call looping through the the second array based on the id gotten from the first
I have tried
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function (output) {
if (output.result === 'success') {
var n = output.data[0].title_count;
$('.blog').empty();
for (var i=0; i<n; i++) {
var storytitle = output.data[i].story_view;
var id = output.data[i].titleID;
var request2 = $.ajax({
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function (output2) {
if (output2.result === 'success') {
var n2 = output2.data[0].episode_count;
for (var i=0; i<n2; i++) {
var titles = output2.data[i].title;
console.log(storytitle + " " + titles);
}
}
else {
console.log('faileds');
}
});
}
} else {
console.log('failed');
}
});
});
The storyTitle has a single value and loops through all the titles when i check my console.
I tried debugging and found out the second for-loop was only executed once, after executing request2.done, it goes back to the first for-loop after the first has finish all its loop, it executes the second for-loop.
I don't know where am missing it.I need help with this.
Finally solved the problem...Changed my code to...
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function (output) {
if (output.result === 'success') {
var n = output.data[0].title_count;
var jsonArray = $(jQuery.parseJSON(JSON.stringify(output.data))).each(function() {
var id = this.titleID;
var CLASS = this.story_view;
var request2 = $.ajax({
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function (output2) {
if (output2.result === 'success') {
var jsonArray2 = $(jQuery.parseJSON(JSON.stringify(output2.data))).each(function() {
var id2 = this.id;
console.log(id + " " + id2);
})
}
})
})
} else {
console.log('failed');
}
});
})
And it worked fine....thanks to Swapnil Godambe

return from function, ajax [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Ajax get data normal, but i dont know how return varname from if statement, with inside loop, with inside function ;).
How can return var username from this statement? Thanks.
$.ajax({
dataType: 'json',
url: 'example.com',
type: 'POST',
success: function (data) {
for (var i = 0; i < data.users.length; i++) {
if (user_id == data.users[i].id) {
var username = data.users[i].username;
return username; // !!!How can return this
};
};
}
})
console.log(username) // error: username is not defined
By default, ajax will be executed asynchronously. This means that the result returned has to be handled in the callback:
$.ajax({
dataType: 'json',
url: 'example.com',
type: 'POST',
success: function (data) {
for (var i = 0; i < data.users.length; i++) {
if (user_id == data.users[i].id) {
var username = data.users[i].username;
console.log(username);
}
}
}
});
ajax could be executed with the async set to false but this is usually not recommended as it will lock the UI until you get the response from the server.
Ajax is asynchronous.
You should use a callback instead.
var callback = function(username) {
// Do something with username here
console.log(username);
}
$.ajax({
dataType: 'json',
url: 'example.com',
type: 'POST',
success: function (data) {
for (var i = 0; i < data.users.length; i++) {
if (user_id == data.users[i].id) {
var username = data.users[i].username;
// call the callback
callback(username);
};
};
}
});
Declare it as a global variable.
var username;
$.ajax({
dataType: 'json',
url: 'example.com',
type: 'POST',
success: function (data) {
for (var i = 0; i < data.users.length; i++) {
if (user_id == data.users[i].id) {
username = data.users[i].username;
return username; // !!!How can return this
};
};
}
})
console.log(username);
Or directly send it to a function in ajax success.

Periodicaly update ajax

I know the there is a lot of questions on this topic, but I really couldn't find anything what fits to my case. I defined this function in javascript:
self.ajax = function(uri, method, data) {
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify(data),
error: function(jqXHR) {
console.log("ajax error" + jqXHR.status);
}
};
return $.ajax(request);
}
And I call this function later like that:
self.ajax(self.tasksGetUri, 'POST', self.jsonRequest).done(function(data) {
for (var i = 0; i < data.tasks.length; i++) {
self.tasks.push({
user_id: ko.observable(data.tasks[i].user_id),
task_id: ko.observable(data.tasks[i].task_id),
done: ko.observable(data.tasks[i].done)
});
}
$(document).ready(function() {
for (var i = 0; i < self.tasks().length; i++) {
task = $("#" + self.tasks()[i].task_id());
if (task.length) {
task.slideUp(400);
task.parent().find(".unFinishedTask").hide();
task.parent().addClass("finished");
task.parent().find(".showTask").show();
}
}
});
});
Well, I want this calling of the function to be performed periodically together with return 'done()' function. I know the there is function setInterval(), but I don't know if it fits in my case. Can somebody recommend me some other solution ?
Thanks in advance for any help.

Categories