Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronous JQuery.post()

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()..

like image 989
Trevor Arjeski Avatar asked Jun 05 '11 17:06

Trevor Arjeski


People also ask

Is jQuery POST synchronous?

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 $.

Is jQuery POST asynchronous?

The jQuery post() method sends asynchronous http POST request to the server to submit the data to the server and get the response.

Is jQuery synchronous or asynchronous?

By default jQuery is not providing synchronous request, so we have to implicitly define synchronous request using $. ajax().

What is jQuery POST?

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.


2 Answers

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.

like image 56
Jakub Avatar answered Oct 22 '22 18:10

Jakub


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

like image 35
Trevor Arjeski Avatar answered Oct 22 '22 19:10

Trevor Arjeski