phinq phinq - 4 months ago 8
jQuery Question

jQuery Ajax run, Why?

I have script following:

var price_option_oc = 0;
// Example
jQuery.ajax({
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

{2}0
{2}0
{1}=9
{1}=9


Why not is:

{1}=9
{1}=9
{2}0
{2}0


Thanks.

Answer

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

So it's very likely that

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

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.

Comments