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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With