phinq phinq - 1 year ago 80
jQuery Question

jQuery Ajax run, Why?

I have script following:

var price_option_oc = 0;
// Example
type: "POST",
processData: false,
dataType: "text",
url: mainURL + url_ajax_get_prices_oc,
data: JSON.stringify(datas),
contentType: "application/json; charset=utf-8",
}).done(function(data) {
console.log('{1}=' + data);
price_option_oc = data;

console.log('{2}' + price_option_oc);

Why result is, I dont know why, please explain for me


Why not is:



Answer Source

Ajax requests run asynchronously to the rest of your code. That is, they run in parallel.

So it's very likely that


is running before the ajax call completes and runs console.log('{1}='+data);

I say "very likely" because, since the ajax call relies on external factors like network speed and the response speed of the remote server, you can't guarantee how fast it will run, and therefore you can't guarantee the order things will run in.

If you need to run code which depends on the response from an ajax call, then you must put that code into your .done function (or into a function which is called from there).

P.S. I would not use async:false to solve this type of issue - this will cause the browser to stop responding to any user input until the ajax call completes (or fails). If the call takes longer than normal, it will look to the user like their browser has crashed. This is not user-friendly. Most coders don't use this feature for that reason.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download