jquery synchronous ajax only appends to html at end of loop [duplicate] - javascript

This question already has an answer here:
How to get jquery to append output immediately after each ajax call in a loop
(1 answer)
Closed 4 years ago.
I need to run a php script multiple times but with a unique ID.
The script takes +- 5seconds to run each time ( downloads some files to server etc .. )
First i did this with an ajax call, but the problem was that this needs to be in sequential order, and with the default ajax settings multiple instances were run at the same time giving strange things.
I changed the parameter 'async' to 'false' which fixed the issue as now the javascript waits for the script to finish before starting the next iteration.
Console alerts pop up every 5-6 seconds and I alert back the data from each post and the loop waits for me to click the alert( good ).
Instead of alerting i try to append the data to a div, it only appends after all iterations have been done.
why?
var arr = ["10","20","30"];
$("button").click(function(){
$.each(arr, function( index, value ) {
console.log( index + ": " + value );
$.ajax({
url: "import_xml_single_post.php",
type: "post",
data: {'import_id' : value},
async: false,
success: function(data){
$( "#result" ).append( data );
//alert(data);
}
});
});
<body>
<button>Click me</button>
<div id="result"></div>
</body>

This is because the browser's UI thread is hogged by the ajax requests, so the browser doesn't have a chance to repaint the page. That's one of the reasons why synchronous ajax is something to avoid using.
There's no need for those requests to be synchronous. If you want them done in series (not in parallel), just fire of a subsequent request when you finish the previous one:
var arr = ["10", "20", "30"];
$("button").click(function() {
var index = 0;
// Start the process
doOne();
function doOne() {
// Get this value
var value = arr[index++];
console.log(index + ": " + value);
$.ajax({
url: "import_xml_single_post.php",
type: "post",
data: {
'import_id': value
},
success: function(data) {
$("#result").append(data);
},
complete: function() {
// Kick off the next request
if (index < arr.length) {
doOne();
}
}
});
}
});
In an cutting-edge environment (or with transpilation), you could use an async function so you could write synchronous-looking code that runs asynchronously:
var arr = ["10", "20", "30"];
$("button").click(async function() {
// ---------------^^^^^
try {
for (const value of arr) {
console.log(value);
await $.ajax({
// -----^^^^^^
url: "import_xml_single_post.php",
type: "post",
data: {
'import_id': value
},
success: function(data) {
$("#result").append(data);
}
});
}
} catch (e) {
// Handle/report error doing request
}
});
It's very important that you have a try/catch around the entire body of the function, because otherwise an error in the ajax call will not be handled (since nothing in jQuery is going to do anything with the promise the async function returns).

Related

Why is my Ajax callback being processed too soon?

I have a general ajax function which I'm calling from loads of places in my code. It's pretty standard except for some extra debugging stuff I've recently added (to try to solve this issue), with a global 'ajaxworking' variable:
rideData.myAjax = function (url, type, data, successfunc) {
var dataJson = JSON.stringify(data),
thisurl = quilkinUrlBase() + url;
if (ajaxworking.length > 0) {
console.log(thisurl + ": concurrent Ajax call with: " + ajaxworking);
}
ajaxworking = thisurl;
$.ajax({
type: type,
data: dataJson,
url: thisurl,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (response) {
ajaxworking = '';
successfunc(response);
},
error: webRequestFailed
});
};
Now, there's one section of my code where a second ajax call is made depending on the result of the first:
getWebRides = function (date) {
var rideIDs = [];
var intdays = bleTime.toIntDays(date);
rideData.myAjax("GetRidesForDate", "POST", intdays, function (response) {
rides = response;
if (rides.length === 0) {
$('#ridelist').empty(); // this will also remove any handlers
qPopup.Alert("No rides found for " + bleTime.DateString(date));
return null;
}
$.each(rides, function (index) {
rideIDs.push(rides[index].rideID);
});
GetParticipants(rideIDs);
});
},
'GetParticipants' (which also calls 'myAjax') works fine - most of the time. But in another part of my code, 'GetWebRides' is itself called directly after another ajax call - i.e. there are 3 calls, each successive one depending on the previous. The 'top-level' call is as follows:
rideData.myAjax("SaveRide", "POST", ride, function (response) {
// if successful, response should be just a new ID
if (response.length < 5) {
// document re-arrangement code snipped here for brevity
getWebRides(date);
}
else {
qPopup.Alert(response);
}
});
so, only when there are three successive calls like this, I'm getting the 'concurrent' catch in the third one:
GetParticipants: concurrent call with GetRidesForDate
and (if allowed to proceed) this causes a nasty probem at the server with datareaders already being open. But why is this only occurring when GetParticipants is called as the third in the chain?
I see, after some research. that there are now other ways of arranging async calls, e.g. using 'Promises', but I'd like to understand what's going on here.
Solved this.
Part of the 'document re-arrangement code' that I had commented out for this post, was in fact calling another Ajax call indirectly (very indirectly, hence it took a long time to find).

I can't seem to break out of A $.each() loop

I can't seem to manage to break out of my each loop if the ajax returns an error. I've tried
return false;
and other similar thing but the $.each still continues to run.
I need to be able to do this so that I can display error messages from my back end after posting it via ajax(I know this is bad practice however a client needed to be able to be able to send multiple forms off at once.).
Can anyone explain what I've done wrong?
var postAll = function(button_clicked)
{
e.preventDefault();
var form_response = [];
var formsCollection = document.getElementsByTagName("form");
$.each(formsCollection, function (key, value)
{
console.log(value.action);
console.log(value.id);
var url = value.action;
var id = value.id;
var data = ($('#' + id + '').serialize());
if (id == 'additionalInfo')
{
data = {'Add_info': $('#Add_info').val(),};
}
if (id != 'DONE')
{
$.ajax({
type: "POST",
dataType: 'json',
url: url,
beforeSend: function (xhr)
{
xhr.setRequestHeader('X-CSRF-TOKEN',$("#token").attr('content'));
},
data: data,
success: function (data)
{
console.log('success'); // show response from the php script.
form_response.push(data); // show response from the php script.
},
error: function (data)
{
console.log('fail'); // show response from the php script.
display_errors(data, id); // show response from the php script.
return true;
}
});
}
});
}
AJAX is asynchronous, when executing your $.each function it will execute the AJAX call and "Not wait" for the others to finish
To solve your problem you'll have to write a function that will execute the first ajax call and in the success it will execute itself again with the second ajax call.
Example:
var data = [form1,form2...etc];
function letsLoop(data,index = 0){
$.ajax({
url:....
success: function(){
letsLoop(data,index+1);
},
error: function(){
}
});
}
and here you call your function:
letsLoop(data,0);
If by breaking out of the loop you mean the return in your error handler, then it won't work as you think it would.
Your loop creates asynchronous requests 'at once'. Then each of these requests is handled by the browser (more or less simultaneously), then come responses. So by the time your error handler runs the loop has long finished.
BTW, the return in your case relates to the error handler, not the function inside the loop.
So, to achieve what you want you should 'queue' your AJAX requests and perform them one by one.
One possible solution is to create an array of forms then take (and remove it from the array) the first one, perform a request, on a response repeat the whole thing, and keep repeating until the array is empty.

blocking javascript execution until response is completed [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
i have js code which returns rows of data for my table. On clicking each of those rows they expand and plan is to show child data of that row by calling another ajax request.
My code for child data looks like below:
function format ( d ) {
var results;
$.ajax({ url: 'http://127.0.0.1:7101/MUDRESTService/rest/v1/feedbacks/' +
d.FeedbackId + '/child/MudFeedbackDetailsVO?onlyData=true',
type: 'get',
dataType: 'json',
success: function(output) {
 console.log(output.items[0].CriticalPath) ;
results = output.items[0];
}
});
return results.CriticalPath;
}
The problem probably is that method doesn't finish by the time value of results.CriticalPath is returned. I can see value in chrome js console so there is no problem with the data part.
So how should i make it return the value once the response is ready
When writing asynchronous code, you need to start working with callbacks rather than return values.
Your functions, like format here, only initiates an action. Updates to the UI are initiated by the callback.
Instead of this logic:
function doSomething() {
var result = format(d);
doSomethingWithResult(result);
}
You need to adapt to this:
function doSomething() {
var result = format(d, doSomethingWithResult);
}
function format( d, callback ) {
$.ajax(..., {
success : function(output) {
var results = output.items[0];
callback(results); // this is where we call doSomethingWithResult
}
});
}
Now I'm no exert at this, but hopefully you'll find something from the code-example that you can use.
I'm binding each row on the .done()-function, which calls another api. I hope this helps.
JS-FIDDLE
(function(){
//getJSON example
var jqxhr = $.getJSON( "https://api.myjson.com/bins/2emll", function(data) {
for (key in data) {
$("#list").append("<li class='" + key + "'>" + data[key] + "</li>");
}
}).done(function( data ) {
$("#list li").on("click", function(e){
var target = e.target.className;
//ajax example
$.ajax({
url: 'https://api.myjson.com/bins/309x5',
type: 'get',
data: target,
dataType: 'json',
success: function(data) {
var title = $("." + target).text();
$("." + target).html(title + '<ul id="ul-' + target + '"></ul>');
}
}).done(function(data){
for (key in data) {
$("#ul-" + target).append("<li class='" + key + "'>" + data[key] + "</li>");
}
});
});
});
})();
you can try setting async option to false
like this
function format ( d )
{
var results;
$.ajax({
url: 'http://127.0.0.1:7101/MUDRESTService/rest/v1/feedbacks/' + d.FeedbackId + '/child/MudFeedbackDetailsVO?onlyData=true',
type: 'get',
dataType: 'json',
async:false,
success: function(output)
{
console.log(output.items[0].CriticalPath) ;
results = output.items[0];
}
});
return results.CriticalPath;
}
NOTE :
but it will make your ajax as synchronous and it may be possible that your browser will be unresponsive for the request so there are some points to be noted before using it
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().
The first letter in Ajax stands for "asynchronous," meaning that the operation occurs in parallel and the order of completion is not guaranteed. The async option to $.ajax() defaults to true, indicating that code execution can continue after the request is made. Setting this option to false (and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.
fore more information you can read here

multiple ajax async not in order and need synchronous behavior

Sorry, My first language is not English. I am not sure that if I explain my question properly.
My code is like a main function have two ajax functions (Use ajax function to get foursquare API)
main(){
ajax1();
ajax2();
all other codes
}
the ajax2() function has to get result from ajax1() as input and then return result(actually result was pushed in to global array).
all other codes should be processed after two ajax functions are finished. I tried the asyn: false but it is not working. My html file include newest jquery like this
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" ></script>
I try the jquery function $.when().done() function and the first ajax works. However, the second ajax() function was in the for loop. The for loop will destroy the mechanism of $.when().done() function:
first ajax: in firstjson function
Second ajax: in transfer function
function firstjson(tmpName,tmpLoc,PhotoJson,foursq){
return $.ajax({
type: 'GET',
url: foursq,
dataType: 'jsonp',
success: function(json) {
for (i = 0; i < 3; i++) {
var resultname = json['response']['venues'][i].name;
var resultlocation = json['response']['venues'][i].location;
var resultlat = resultlocation.lat;
var resultlng = resultlocation.lng;
var tmpmarker = new google.maps.LatLng(resultlat,resultlng)
tmpName.push(resultname);
tmpLoc.push(tmpmarker);
var resultid = json['response']['venues'][i].id;
var tmpPhotoJason = 'https://api.foursquare.com/v2/venues/'+ resultid +'/photos?';
PhotoJson.push(tmpPhotoJason);
}
}
});
}
function transfer(PhotoJson,PhotoURL){
for (i = 0; i < 3; i++) {
return $.ajax({
type: 'GET',
url: PhotoJson[i],
dataType: 'jsonp',
success: function(json) {
resultphoto = json['response']['photos']['items'];
photoprefix = resultphoto[i].prefix;
photopresuffix = resultphoto[i].suffix;
photourl = photoprefix+"150x150" + photopresuffix;
PhotoURL.push(photourl);
}
});
}
}
$.when(firstjson(tmpName,tmpLoc,PhotoJson,foursq)).done(function(){
alert("test1");
$.when(transfer(PhotoJson,PhotoURL).done(function(){
console.log(PhotoURL);
all other codes!!!!
});
});
//PhotoURL is global array
So the first "when" function work properly. alert("test1") work after the firstjson was done. However the for loop inside transfer function will break the when function. How can I fix the problem. Please help me. I will appreciate you can give me any related information. Thanks!!!
This will execute ajax2 after ajax1
function anotherMethod(){
//Here you do all that you want to do after the last $ajax call
}
main(){
firstjson(tmpName,tmpLoc,PhotoJson,foursq)
.then(transfer(PhotoJson,PhotoURL))
.then(anotherMethod);
}
As you are returning a promise from the first with the "return $ajax..."
So you organice your code like this:
in methods with ajax calls you return the call as you are doing now
return $.ajax();
that returns a promise that you chain.
And you put what you want to do in another method so you call it in the last "then".
Non-Blocking Example
You should use non-blocking code. You can turn async off (async: false) but this can easily be done in a non-blocking manor using callback functions.
function main(){
$.ajax({ // First ajax call (ajax1)
url: "first/ajax/url",
type: "GET", // POST or GET
data: {}, // POST or GET data being passed to first URL
success: function(x){ // Callback when request is successfully returned
// x is your returned data
$.ajax({ // Second ajax call (ajax2)
url: "second/ajax/url",
type: "GET", // POST or GET
data: {
thatThing: x
}, // POST or GET data passed to second URL
success: function(y){
// y is your second returned data
// all other codes that use y should be here
}
});
}
})
}
This would be the non-blocking approach, nest your function within "success" callback functions. Nest ajax2 within ajax1's "success" callback to ensure that ajax2 is not executed before ajax1 has returned and nest your "all other codes" inside the "success" callback of ajax2 to ensure they are not executed until ajax2 has returned.
Blocking Example
If you absolutely must (please avoid at all cost) you can disable async which will block all JavaScript code from executing until the ajax has returned. This may cause your browser to temporarily freeze until the ajax request has returned (depending on the browser).
function main(){
var x = ajax1();
var y = ajax2(x);
window["y"] = y; // push to global as you requested but why?
// All other codes that can now use y
}
function ajax1(){
var x;
$.ajax({
url: "first/ajax/url",
async: false,
type: "GET", // POST or GET,
data: {}, // POST or GET data being passed to first URL
success: function(r){x=r}
});
return x;
}
function ajax2(x){
var y;
$.ajax({
url: "second/ajax/url",
async: false,
type: "GET", // POST or GET,
data: {
thatThing: x
}, // POST or GET data being passed to second URL
success: function(r){y=r}
});
return y;
}
Once again I stress, try not to disable async that will cause your code to block and is BAD code. If you absolutely 100% have to for some reason than than it can be done but you should attempt to learn how to write non-blocking code using callbacks as the first example does.
Social Network Example
Now I'll do an example of an ajax call to get an array of your friends IDs, and then a series of ajax calls to get each of your friends profiles. The first ajax will get the list, the second will get their profiles and store then, and then when all profiles have been retrieved some other code can be ran.
For this example, the url https://api.site.com/{userID}/friends/ retrieves an Object with a list of friends IDs for a particular user, and https://api.site.com/{userID}/profile/ gets any users profile.
Obviously this is a simplified api as you will probably need to first establish a connection with a apikey and get a token for this connection and the token would likely need to be passed to the api uris but I think it should still illustrate the point.
function getFriends(userID, callback){
$.ajax({
url: "https://api.site.com/"+userID+"/friends/",
success: function(x){
var counter = 0;
var profiles = [];
for(var i=0;i<x.friendIDs.length;i++){
$.ajax({
url: "https://api.site.com/"+x.friendIDs[i]+"/profile/",
success: function(profile){
profiles.push(profile);
counter++;
if(counter == x.friendIDs.length) callback(profiles);
}
});
}
}
});
}
getFreinds("dustinpoissant", function(friends){
// Do stuff with the 'friends' array here
})
This example is "Non-blocking", if this example were done in a "blocking" way then we would ask for 1 friends profile, then wait for its response, then request the next and wait and so on. If we had hundreds of friends you can see how this would take a very long time for all ajax calls to complete. In this example, which is non-blocking, all requests for profiles are made at the same time (within 1ms) and then can all be returned at almost exactly the same time and a counter is used to see if we have gotten responses from all the requests. This is way way way faster than using the blocking method especially if you have lots of friends.

JavaScript for loop with innerHTML not updating during loop execution

I'm looping through an array, and during each iteration of the loop, I'm calling a url through ajax. I'd like to also update an .innerHTML such that it displays to keep the user informed as to which iteration of the loop is being processed. However, .innerHTML only displays the update when the script completes.
How can I make this notification display during my loop?
I'm also using the query ajax setting 'async: false'. I don't want to hammer my server with processing all of the ajax requests at once, as they are encoding video files which is CPU intensive. I don't really want to lock the browser up waiting for synchronous requests to complete either.
Is there a better way to do this?
My ultimate goal is to sequentially execute my combine.php script for each set of videos, while displaying a current status indicator to the user, and while not locking the browser up in the process. Your help is appreciated!
Code snippet here:
// process the loop of videos to be combined
var status = document.getElementById('currentStatus');
for (i=0; i< count; i++) {
// change the display
var fields = videos[i].split(":", 2);
current = i +1;
currentStatus.innerHTML = "<b>Multi-part Videos:</b> <h3 class='status'>Currently Updating Bout #" + fields[1] + " (" + current + " of " + count + " videos)</h3>";
// run the combine
var dataString = 'videoId='+ fields[0];
$.ajax({
type: "POST",
url: "combine.php",
data: dataString,
success: function(txt) {
//deselect the checkbox
document.combine.video[selected[i]].checked = false;
},
async: false
});
async: false will hang the entire browser until the ajax request completes. That is why you don't see the page update on each loop iteration.
Synchronous ajax requests typically make for terrible UX (do you like the page to freeze inexplicably?) and there is almost always a better way to do it. Since you're using jQuery, the Deferred Object API makes this easy.
As others have alluded, your problem is caused because JavaScript is single threaded - while the single JS thread is waiting for your ajax request to return, it's not allowed to update the UI.
You can get around this by changing the request to async, and using the callback to trigger the request for the next object:
// trigger the loop of videos to be combined
var status = document.getElementById('currentStatus');
processVideo( 0 );
function processVideo( index ) {
var fields = videos[index].split(":", 2);
currentStatus.innerHTML = "<b>Multi-part Videos:</b> <h3 class='status'>Currently Updating Bout #" + fields[1] + " (" + current + " of " + count + " videos)</h3>";
// run the combine
var dataString = 'videoId='+ fields[0];
$.ajax({
type: "POST",
url: "combine.php",
data: dataString,
success: function() {
processResponse( index);
},
async: true
});
}
function processResponse( index ) {
// this method is called each time the ajax request finishes
if (index++ < count) {
//deselect the checkbox
document.combine.video[selected[index]].checked = false;
processVideo( index );
}
}
If you want to update one by one while async is set to true, the next request can be put in the success callback function. The update status code should be inside that function too.
function ajaxRequest(i){
// other processing
.............
$.ajax({
type: "POST",
url: "combine.php",
data: dataString,
success: function(txt) {
//deselect the checkbox
document.combine.video[selected[i]].checked = false;
// update status
currentStatus.innerHTML = .....
// make next request
if(i<lastOne){
ajaxRequest(i+1);
}
},
async: true
});
}

Categories

Resources