how to make a jquery "$.post" request synchronous [duplicate] - javascript

This question already has answers here:
How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
(14 answers)
Closed 9 years ago.
I’ve been googling this and avoiding this error in my bug fix list for a long time now, but I’ve finally reached the end of the list, the last of which I have to make a function return true/false to state whether the validation has succeeded or not.
I'm using ajax to compare certain fields with those that are already in the db and by default the $.post() method does it's operations asynchronously.
I’m setting a variable inside the call onSuccess and the calling method doesn't get a response because of this, so all my js/jquery fails on pageLoad... I would prefer if I could still keep using the $.post method.

jQuery < 1.8
May I suggest that you use $.ajax() instead of $.post() as it's much more customizable.
If you are calling $.post(), e.g., like this:
$.post( url, data, success, dataType );
You could turn it into its $.ajax() equivalent:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType,
async:false
});
Please note the async:false at the end of the $.ajax() parameter object.
Here you have a full detail of the $.ajax() parameters: jQuery.ajax() – jQuery API Documentation.
jQuery >=1.8 "async:false" deprecation notice
jQuery >=1.8 won't block the UI during the http request, so we have to use a workaround to stop user interaction as long as the request is processed. For example:
use a plugin e.g. BlockUI;
manually add an overlay before calling $.ajax(), and then remove it when the AJAX .done() callback is called.
Please have a look at this answer for an example.

If you want an synchronous request set the async property to false for the request. Check out the jQuery AJAX Doc

From the Jquery docs: you specify the async 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: url,
success: function(result) {
if(result.isOk == false)
alert(result.message);
},
async: false
});
}
this is because $.ajax is the only request type that you can set the asynchronousity for

Related

How to specify an asynchronous request in API JavaScript [duplicate]

This question already has answers here:
How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
(14 answers)
Closed 6 years ago.
I want to send to server (php) a request AJAX from an api javascript:
JS File :
var commit = new Object();
commit.id= this.id;
commit.action = this.doCommit;
commit.vrp= this.vrp;
$.post(this.ajaxURL, commit);
with this code i can send a request but in mode asynchroun. I searched on internet and I found a solution :
$.ajax({
type: 'POST',
url: this.ajaxURL,
data: commit,
async:false
});
I don't know if it is the best solution, or I can precise async:false in a $.post request, if yes , how ?.
So you do or you do not want to send the request asynchronously? The question seems to be confusing for me. But by default, $.ajax({... is always async, and $.post is just a shorthand way to write a simple post ajax request, which is also async. If you use the async:false, you are telling the javascript to not continue to execute the next line of code until the request finishes.

Is there a default timeout for jQuery`s getScript method? [duplicate]

This question already has answers here:
JQuery ajax call default timeout value
(5 answers)
Closed 7 years ago.
I am using jQuery's getScript() method to load some third part js library, I am wondering whether there's a default time out value for this method. I don't really believe getScript will keep waiting until it gets a response, but I need to know how long before it quit and if that value is not ideal to me, is there a way to configure it? Maybe something like this?
$.ajaxSetup({
cache: true
});
According to jQuery documentation
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
dataType: "script",
success: success
});
So it uses the default timeout which you can override as usually you do for jQuery.ajax.

Synchronous jQuery calls, without putting everything in the callback

Is it possible to get a JSON in jQuery synchronously without using the async: false option (which apparently has been deprecated)? I also would prefer not to put everything into the success function.
No, there is no other option than async: false. I wouldn't recommend it if there were.
For the success function, you can simply pass another function that will be executed.
For example:
$.ajax( {
url: myUrl,
type: 'POST',
success: myFunc
} );
function myFunc( datas ) {
// do what you should do in a success function
}
Since ajax methods on jQuery return a Deferred Object (jQuery 1.5+) you could also write
$.ajax({
url: myUrl,
type: 'POST'
}).done(function() {
// do what you should do in a success function
});
Not reasonably. Trying to force the request to be Synchronous without using asyc:false is possible, but a waste of effort in my opinion. In pretty much every scenario you want to use async:true, you will be able to accomplish all of the same things with async:true as you can with async:false. It's just a matter of how you structure your code.
If you look at the current version of the source file that executes the AJAX request:
https://github.com/jquery/jquery/blob/master/src/ajax/xhr.js
You will see it still uses the async field on the settings object, this field is passed directly into the Open method of the XMLHttpRequest object. So using the default implementation all you can do, is set "async: false".
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
Now assuming you are really stubborn and want to do this without setting "async:false", you could get really bold and write a custom ajaxTransport and register it with a custom data type.
Here is an example I wrote that creates a custom transport object with a send and abort method, and registers it with the dataType 'mine'. So when you specify dataType 'mine' in your ajaxSettings object it will use this custom transport instead of the one built into jQuery. http://jsfiddle.net/xrzc7/ Notice there are two ajax requests one with the 'mine' dataType that show the alert, and one without the data type that does not show the alert. My ajaxTransport in this example isn't fully functional, its just to illustrate that you can swap in your own send function.
I wouldn't advise writing your own ajaxTransport for jQuery because it really isn't neccessary in my opinion, but to answer your question I'm suggesting it as an option.
You should pay close attention to how the default ajaxTransport in jquery is written, and how it interacts with the settings object and callback methods when writing your custom ajaxTransport. Your send function would obviously force a "false" value as the async parameter of the XMLHttpRequest.open method.
https://github.com/jquery/jquery/blob/master/src/ajax/xhr.js - this is the current source code for the default ajaxTransport mechanism.
Hope this helps, or perhaps persuades you to always use async:true. :-D

get data returned inside success of $.ajax jquery

I have a question here. Let's say I have some Ajax with jQuery like so:
var jqXHR = $.ajax({
type: 'POST',
success: function(data) {
if(data != true)
{
return false;
}
}
});
I know that $.ajax returns a jqXHR object. My question is the following:
Is it possible to get the returned value of the success function of my $.ajax call using that jqXHR object? If so, how do I do that? If that's not possible using the jqXHR object, is there any way that I can get access to the returned value of my success function WITHOUT SETTING async: false in $.ajax?
Any help please?
It is not possible without setting async to false. I would suggest not to set it to false because it stops the page completely until the server response comes. Sometimes it even hangs the browser if the connection is slow or server takes time to respond due to heave operation.
You can execute your code in the success handler of ajax which you are planning to do it outside.
It is possible - in a way - returned jqXHR is also a deferred object so you could do
jqXHR.then(function(data) { ... });
the only other way to get access to the data that i know of apart of the ajax callbacks, the cool thing is that you can use it multiple times after the ajax request was sent and it will always return the data you've received from the server.

jQuery: getJSON + SunlightLabs API help requested

I'm having trouble pulling a specific element from an API call using jQuery's getJSON function. I'm trying to use SunlightLab's congress API to pull specific info about legislators. In the example below I'm trying to pull a legislator's website:
$.getJSON("http://services.sunlightlabs.com/api/legislators.get.json?apikey=[api key]&lastname=Weiner&jsonp=?" , function(data) {
alert("hello from sunlight");
alert(data.response.legislator.website);
});
Using the above code, the first alert shows up but the second alert does not even occur. I understand that getJSON should be using JSONP in this instance, and I think I have that set up correctly, ending my URL with '&jsonp=?'.
Putting the URL in my getJSON function into a web browser gives me this:
?({"response": {"legislator":
{"website":
"http://weiner.house.gov/", "fax":
"202-226-7253", ... etc.
I'm a little thrown by the '?' showing up at the beginning of this, but if the first alert is showing up then the request must be succeeding...
The URL you're using is setting the JSONP callback to be equal to ?, which means its injecting a JavaScript function called ? with an argument of a JavaScript object. This is invalid. So, the request is succeeding, but the wrapper function you've defined isn't being called (and isn't valid).
You could change the URL so that its jsonp=callback (or some other handler function name), and then define a function called callback that handles an argument that expects the object.
One way to (automatically) trigger JSONP support in jQuery is to switch the key to be called 'callback' so that it signals to jQuery that you're doing a JSONP call. ie, callback=callback.
EDIT: As Drackir points out, jQuery provides a setting in $.ajax for letting it define it's own callback function name, but you need to signal to it that its a JSONP call by setting dataType: 'jsonp' in the $.ajax call.
The question mark is there because you specified the JSONP callback function to be ? in your query string (ie. &jsonp=?). Due to security concerns (specifically the same-origin policy) you cannot do an AJAX request to a site outside the same domain as the page you're on. To get around this, JSONP works by creating a script tag, with the SRC set to the URL of the script on the other site. This will load the external JavaScript file and run whatever code is there. Now, in order to link that external code with your JavaScript, the external API takes the name of a function to call (&jsonp=functionnametocall). The returned JavaScript calls that function and passes in the data it's trying to return as a JSON object as the first argument.
So, the reason you see the question mark when you go there is because you're passing a question mark to the jsonp query string parameter. jQuery will automatically convert the question mark in a url such as http://www.test.com/api/apikey=292929&callback=? to a uniquely named function. This is handled in the background by jQuery so you don't have to think about it.
Now, that said, I don't know if jQuery detects if the name of the callback parameter as being something other than callback=?. $.getJSON() however is a short form for the longer:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
I suggest you try using $.ajax() directly and set the jsonp setting equal to "jsonp". This tells the $.ajax() method that the query string parameter is called jsonp and not callback. So like this essentially:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback,
jsonp:"jsonp"
});
More information: $.getJSON | $.ajax()
OK, OK, so it was a rather simple fix, adding a line to the the example given by #Drackir. The missing piece was 'cache: true' within the ajax settings. The final working code looked like this:
$.ajax({
url: 'http://services.sunlightlabs.com/api/legislators.get.json?apikey=[api key]7&lastname=Weiner',
dataType: 'jsonp',
cache: true,
jsonp: 'jsonp',
success: function(data) {
alert("hello from ajax") ;
alert(data.response.legislator.website);
}
});
I'm not sure why 'cache: true' is needed in this case. Thanks for the help.

Categories

Resources