phinq phinq - 6 months ago 10
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:




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.