I'm writing a little script that makes individual AJAX calls through a loop and I came across a, most likely obvious, problem. It seems that the loop is going to fast to handle the data that is received with ajax, causing it to only load the last piece of data in the loop. I added an alert box that steps through the iterations and that loads the data fine, but it wouldn't be practical in a user environment. The code is simply a jquery .post() with a callback inside a for-loop. I can post code upon request, but I feel like this can be cleared up verbally. Any one know a workaround or better approach to loading data sequentially?
EDIT
Does .ajaxSetup()
modify .post()
? Perhaps I can use that to change the async value for .post()..
post() method does it's operations asynchronously. I'm setting a variable inside the call onSuccess and the calling method doesn't get a response because of this, so all my js/jquery fails on pageLoad... I would prefer if I could still keep using the $.
The jQuery post() method sends asynchronous http POST request to the server to submit the data to the server and get the response.
By default jQuery is not providing synchronous request, so we have to implicitly define synchronous request using $. ajax().
jQuery post() method. The post() method is one of the commonly used HTTP methods. It is used to load a page from the server using an HTTP POST request. This method never caches the data and is generally used to send the data with the request.
You need to force your ajax call to be synchronous my friend ;)
http://api.jquery.com/jQuery.ajax/
ex:
asyncBoolean Default: true
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.
I actually found that adding this snippet worked so I didn't have to change my .post() to .ajax()
$.ajaxSetup({
async: false
});
I'm not sure if it will also change the settings of my other ajax calls though
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