BlackBelt2025 BlackBelt2025 - 3 years ago 112
Javascript Question

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

Answer Source

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download