$.ajaxSetup({async:false}); stops mousemove event
Solution 1
return
implies synchronous code flow. AJAX is asynchronous without async: false
, however. This does not mean you should use async: false
. Rather, you should change your code flow to use callbacks instead of return values.
This is needed since there is no way to make the asynchronous code synchronous (i.e. you can't use return
with asynchronous functions). The only way is to provide a callback yourself as well:
function get(url, callback) {
$.get(url).success(function(data) { callback(data); });
}
Like:
get("...", function(result) {
// use `result` which you normally got by assigning the return value
// of `get` to a variable
});
Solution 2
You should find a way to do what you want without setting async:false
.
Using the callbacks from your ajax request you should be able to do most things.
Solution 3
async:false
halts the browser, and all JavaScript, until the AJAX call is done. There's no way around this.
What you should do is, instead of trying to return a value from an AJAX call, you should do all processing of the data inside your callback.
You can save the returned data to a global variable, but it won't be available until it's done.
Related videos on Youtube
Oleksandr IY
Updated on June 04, 2022Comments
-
Oleksandr IY almost 2 years
This code stops mousemove event
$.ajaxSetup({async:false}); $.get(url).success(function(data) { result = data; });
Is there a way to avoid this but keep $.ajaxSetup({async:false});, like a load function?
Thanks
Additions:
what if I need
$.ajaxSetup({async:false}); $.get(url).success(function(data) { result = data; }); $.ajaxSetup({async:true}); return result
how to handle that?
Thanks
-
Tomalak over 12 yearsYou do not want
$.ajaxSetup({async:false})
. -
Tomalak over 12 years@Oleksandr: No, you don't. I challenge you to name one single reason.
-
Tomalak over 12 years@Oleksandr You are lacking basic knowledge about how asynchronous JavaScript works. Switching it off because you don't understand it will hurt you, because asynchronous calls are a good thing to have.
-
Tomalak over 12 years@Oleksandr *sighs* You never need synchronous Ajax requests in a JavaScript application. There is not a single valid use for them. The problem you outline in your question is extremely common, it has been solved and the solution does not involve a synchronous request. Trust me.
-
-
Oleksandr IY over 12 yearshave added addition to my question, please check