Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if function is jQuery ajax request

I am writing an ajax queue and I want to ensure that the type of function (comes in an object) is in fact an ajax request so that .done/.fail/.always can be called on it. How can I do this?

like image 241
BarryBones41 Avatar asked Feb 01 '16 15:02

BarryBones41


People also ask

How do I know if AJAX request is running jQuery?

jQuery ajaxStop() Method The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.

Is not a function AJAX?

The "$. ajax is not a function" error occurs when loading the slim version of jQuery and trying to use the ajax function. The ajax function is excluded from the slim jQuery version. To solve the error load the regular jQuery version on your page.


1 Answers

I want to ensure that the type of function (comes in an object) is in fact an ajax request so that .done/.fail/.always can be called on it.

jQuery ajax request objects (jqXHR) aren't functions. In jQuery v1.12.0 (the version I had handy to check), they're plain objects with properties added (e.g., no special constructor), so you can't use instanceof to see if they're jqXHR objects.

You can test whether done, fail, and/or always are present on the object you get:

if (obj.done && obj.fail && obj.always) {
    // It's probably a jqXHR
}

Or if you wanted to be more thorough you might make sure they were functions:

if (typeof obj.done == "function" &&
    typeof obj.fail == "function" &&
    typeof obj.always == "function") {
    // It's probably a jqXHR
}

This is an example of "duck typing": It quacks like a duck, so we'll assume it's a duck.

If you want to really limit it as much as you can to jqXHR objects and not other things that have those functions, you could check for other functions/properties that they have, such as getAllResponseHeaders and such.

like image 142
T.J. Crowder Avatar answered Oct 08 '22 15:10

T.J. Crowder