I have a JavaScript widget which provides standard extension points. One of them is the beforecreate
function. It should return false
to prevent an item from being created.
I've added an Ajax call into this function using jQuery:
beforecreate: function (node, targetNode, type, to) {
jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
function (result) {
if (result.isOk == false)
alert(result.message);
});
}
But I want to prevent my widget from creating the item, so I should return false
in the mother-function, not in the callback. Is there a way to perform a synchronous AJAX request using jQuery or any other in-browser API?
Keep in mind that if you're doing a cross-domain Ajax call (by using JSONP) - you can't do it synchronously, the
async
flag will be ignored by jQuery.For JSONP-calls you could use:
Because
XMLHttpReponse
synchronous operation is deprecated I came up with the following solution that wrapsXMLHttpRequest
. This allows ordered AJAX queries while still being asycnronous in nature, which is very useful for single use CSRF tokens.It is also transparent so libraries such as jQuery will operate seamlessly.
Firstly we should understand when we use $.ajax and when we use $.get/$.post
When we require low level control over the ajax request such as request header settings, caching settings, synchronous settings etc.then we should go for $.ajax.
$.get/$.post: When we do not require low level control over the ajax request.Only simple get/post the data to the server.It is shorthand of
and hence we can not use other features(sync,cache etc.) with $.get/$.post.
Hence for low level control(sync,cache,etc.) over ajax request,we should go for $.ajax
Note: You shouldn't use async due to this:
Chrome even warns about this in the console:
This could break your page if you are doing something like this since it could stop working any day.
If you want to do it a way that still feels like if it's synchronous but still don't block then you should use async/await and probably also some ajax that is based on promises like the new Fetch API
this is my simple implementation for ASYNC requests with jQuery. I hope this help anyone.
With
async: false
you get yourself a blocked browser. For a non blocking synchronous solution you can use the following:ES6/ECMAScript2015
With ES6 you can use a generator & the co library:
ES7
With ES7 you can just use asyc await: