BarryBones41 BarryBones41 - 1 month ago 6
Javascript Question

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?

Answer

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.