jquery ajax return value and done function - javascript

I found this little example on jquery documentation page. I always tried returning value from ajax function and I was always told that there is some problem of sync and async thing and I can't return value out of $.ajax function without making it async.
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});
In the example above, on what this done function is applied(whats being used as $(this) in example).
one more thing, as the ajax function can't set global variables, can't the be set in this done too? cant I return value out of done function either?

what this done function is applied
$.ajax returns a jqXHR object (see first section after the configuration parameter description) wich implements the promise interface and allows you to add callbacks and get notified of changes of the Ajax call.
whats being used as $(this) in example
Inside the callbacks for $.ajax, this refers to the object context refers to in the configuration or the jqXHR instance if context was not set. In this case it refers to document.body:
context: This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).
This and more is all explained in the documentation: http://api.jquery.com/jQuery.ajax/
as the ajax function can't set global variables
That is not correct, any function can set global variables. The problem with asynchronous functions is that you are likely accessing the variable before it was set.
can't the be set in this done too
See above
cant I return value out of done function either
You can return a value (as in putting a return statement inside the callback), but you cannot return it to your code, since jQuery is calling the callback internally and just ignoring the return value.

Related

Javascript return reference to jqXHR from function

Recently I abstracted a bunch of AJAX calls into a function using the $.post() method. My idea was to use the jqXHR object returned by $.post() to add standard error handlers and such (via .fail() .done() .always()) to remove code duplication. I then thought that I could return the jqXHR object from the method to the original calling function so I could add additional handlers to do more context-specific things.
However, the jqXHR object returned seems to be a copy of the original object, not the object itself. As such, its state never gets updated by the original call so none of my additional .done() functions get executed.
Is it possible to return a reference to an object in JS? I have a C++ background, so is there a way to mimic the "return pointer to object" functionality in JS?
I know there have been discussions on pass-by-reference/value on here, but I couldn't find one dealing specifically with Deferred objects
EDIT: example code
function AJAX(url,data,onSuccess) {
var jqxhr = $.post({url,data});
jqxhr.done(onSuccess);
jqxhr.fail(displayError());
return jqxhr;
}
...
function example() {
var dfrd = AJAX("example.php",data,successFunc);
dfrd.done(alert("Hello, World!"));
}
The .done() & .fail() within the AJAX function get executed normally, but the .done() within example() never executes because dfrd.state() is always pending
So this turned out to be a timing issue.
It appears that, with multiple .done() functions, there is a slight delay when the function receives a response from the $.post() call. So my onSuccess(resp) {} that was passed to the AJAX function would execute after the alert(). The particular onSuccess function I was using to test had a page refresh call in it, which would close the alert before I could see it.
I have a C++ background, so I guess I need to upgrade my JS testing procedures.
Thanks to all who commented!

When to assign functions to variable, using jquery

so I've been messing around with some Jquery Ajax promises/deffers etc... and i've come across something I don't completely understand, not strictly related to the Jquery Ajax.
I have always declared and called functions like so:
function foo1() { //sets function
alert('foo1');
}
foo1(); //calls function
But it seems the more I see different code a lot of people are declaring functions like the following, I just copied and pasted an example I saw so I would't miss anything:
var promise = $.ajax({
url: "/myServerScript"
});
promise.done(myStopAnimationFunction);
I understand what the above does, just an example.
The question is, is it better to assign functions to variables? What are the pros/cons, and in what situations is this way used?
At what point in this code is the actual function called. Does
promise.done(myStopAnimationFunction);
call both the ajax function, and then the callback, or just the callback?
Thanks
In your example, you're assigning your promise variable to what $.ajax returns (which is a jqXHR object)
var promise = $.ajax({
url: "/myServerScript"
});
Your then saying that once it's done, you want to call myStopAnimationFunction. Because $.ajax is async by default, the browser will skip right over this and only call your myStopAnimationFunction when the request is complete.
promise.done(myStopAnimationFunction);
Now, with your myStopAnimationFunction; you could always just do the following:
promise.done(function(){
$('.loader').hide();
});
but if you have code which you'll be using a lot, put it in a function so you don't need to repeat yourself (see DRY) - this has nothing to do with jQuery, however.
Your example is exactly the same as doing:
$.ajax({
url: "/myServerScript"
}).done(function(){
$('.loader').hide();
});
Those are two very different things! The first one is a function declaration. The second one is a function invocation, and what is assigned to the promise variable is the value returned by the function you're calling ($.ajax).
In any case, it is possible to assign functions to variables too (but I'm not sure if that's what you're really asking – if it is, this is a duplicate of var functionName = function() {} vs function functionName() {}).
Does promise.done(myStopAnimationFunction);
call both the ajax function, and then the callback, or just the callback?
Neither. That line is a call to done on the promise object, to register a callback to be called when the ajax response arrives. At that point you call done, the ajax request may have already fired, and the response even might already be available (if that's the case, the callback will be called immediately).

Run code after black box AJAX request returns

I have a function which makes an AJAX request to a server and returns relevant information after it completes.
I have another function which manipulates some variables in its namespace based on the returned information.
Currently, I am appending a 'callback' argument to the first function, which is called when the request completes. This, however, blurs the purpose of the first function - instead of being a 'getInfo' function, it's become a 'getInfoAndDo' function.
Ideally, I'd like to call the second function (a 'do' function, which calls the first function, a 'get' function) and does its thing.
I have looked around and found jQuery methods such as .ajaxStop and .ajaxComplete, but they seem to only to work when bound to DOM elements. Is there any way to do this entirely in javascript?
e.g.
function _getEventAttendance(uid, callback) {
var attendQuery = FB.Data.query('SELECT eid,rsvp_status,start_time FROM event_member WHERE uid = {0}', uid);
FB.Data.waitOn( [attendQuery],
function (args){
callback(args[0]);
}
);
}
function logAttendance(attendance){
console.log(attendance);
}
Currently, I am doing:
_getEventAttendance(123456789, logAttendance);
which seems ridiculous to me.
Is there a way to write the code such that I can change the code snippet inside _getEventAttendance / remove the callback argument:
FB.Data.waitOn( [attendQuery],
function (args){
return args[0];
}
);
and then make calls that are equivalently as simple as :
logAttendance.ajaxComplete(_getEventAttendance(123456789));
(I'm just making up the syntax for this, I have no idea how it's supposed to be written.)
$.when(<AJAX Request>).then(function(response){...});
Optionally use $.pipe() to filter response first.

Retrieve data from $.ajax function in javascript

I have used $.ajax function to fetch data from C# in asp.net MVC3.0, Now I want is to get the value from the success function of $.ajax and used it in another function defining global variable and putting the result in it is not working so please let me know how can I get the value.
Invoke a callback function from within the success function. Most likely you are treating everything as synchronous when infact Ajax is asynchronous.
Low down dirty way would probably be to specify async:false

How can we pass multiple parameters to onSuccess method of PageMethod?

I'm calling PageMethod "SameMethod" from javascript method "caller" so that I can get some values from DB. After I get values, control is continuing in "onSuccess" method. Problem is that I need to use some variable values ("importantValue") from javascript method "caller" in "onSuccess" method.
function caller(){
var importantValue = 1984;
PageMethod.SomeMethod(param1,..., onSuccess, onFailure)
}
onSuccess method should be something like this:
function onSuccess(pageMethodReturnValue, importantValue ){
}
Is it possible and, if it is, how to pass multiple parameters (besides return values of page method) to "onSuccess" method of PageMethod?
Thanks for help
Pass your importantValue as an additional parameter when calling the PageMethod. (this is usually called the context parameter if you are searching online for more info)
function caller(){
var importantValue = 1984;
PageMethod.SomeMethod(param1,..., onSuccess, onFailure, importantValue)
}
Then you can access the value in the onSuccess callback as follows:
function onSuccess(pageMethodReturnValue, context, methodName){
// context == 1984
}
Update to explain onSuccess parameters for #JacksonLopes
There is a good description on the aspalliance website in an article by Suresh Kumar Goudampally
The important bit (modified to use my parameter names) is:
The success call back method has three parameters:
pageMethodReturnValue - Returns the output of the page method.
context - This is used to handle different logic when single callback is used for multiple page method requests. We can also pass
an array of values as the context parameter.
methodName - This parameter returns the name of page method called.
You could use an anonymous function
PageMethod.SomeMethod(param1,..., function(){onSuccess(foo, importantValue)}, onFailure)

Categories