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

method. My idea was to use the
object returned by
to add standard error handlers and such (via
) to remove code duplication. I then thought that I could return the
object from the method to the original calling function so I could add additional handlers to do more context-specific things.

However, the
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
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
on here, but I couldn't find one dealing specifically with

EDIT: example code

function AJAX(url,data,onSuccess) {
var jqxhr = $.post({url,data});
return jqxhr;
function example() {
var dfrd = AJAX("example.php",data,successFunc);
dfrd.done(alert("Hello, World!"));

within the AJAX function get executed normally, but the
never executes because
is always

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