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?
ajax({ type: "POST", async: "false", url: "checkpass. php", data: "password="+password, success: function(html) { var arr=$. parseJSON(html); if(arr == "Successful") { return true; } else { return false; } } }); $. ajaxSetup({async: true});
AJAX can access the server both synchronously and asynchronously: Synchronously, in which the script stops and waits for the server to send back a reply before continuing. Asynchronously, in which the script allows the page to continue to be processed and handles the reply if and when it arrives.
Ajax requests are Asynchronous by nature, but it can be set to Synchronous , thus, having the codes before it, execute first.
Synchronous AJAX call is made when async setting of jQuery AJAX function is set to false while Asynchronous AJAX call is made when async setting of jQuery AJAX function is set to true. Default value of the async setting of jQuery AJAX function is true. jQuery Synchronous AJAX call.
You can put the jQuery's Ajax setup in synchronous mode by calling
jQuery.ajaxSetup({async:false});
And then perform your Ajax calls using jQuery.get( ... );
Then just turning it on again once
jQuery.ajaxSetup({async:true});
I guess it works out the same thing as suggested by @Adam, but it might be helpful to someone that does want to reconfigure their jQuery.get()
or jQuery.post()
to the more elaborate jQuery.ajax()
syntax.
From the jQuery documentation: you specify the asynchronous option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.
Here's what your code would look like if changed as suggested:
beforecreate: function (node, targetNode, type, to) { jQuery.ajax({ url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value), success: function (result) { if (result.isOk == false) alert(result.message); }, async: false }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With