JQuery statusCode 404 - how to get jqXhr url?

I have a jquery ajax statuscode function to handle a 404... another Stack Overflow answer states that in the success method, this.url gives the url for the request... however, this doesn't seem to be the case for my statusCode handler. Any ideas? Nothing that I can see in documentation about how to get the url for the request.

My ajax option object looks roughly like this (may have missed off a brace when trimming out code not relevant to this question)

;(function($) {
    var defaultSettings = {
     // ... other plugin specific settings
    ajaxOptions:
    {
                    cache:false,
                    context:$(this),
                    statusCode: {
                        404:function(xhr) {

                      // this line...  this.url is always undefined  (so is xhr.url)
                            $('#body').append('<div class="errordisplay">Content not found' + (this.url?': ' + this.url:'') + '</div>');

                    // ... do other stuff

                            return false;

                        }
                    }
            }
}

Answers


The default context for AJAX event handlers (i.e. the object bound to this in the handlers) indeed exposes an url property because it is a mix between $.ajaxSettings and the arguments passed to $.ajax().

However, in your case, you're overriding that default context by passing $(this) in the context option. Moreover, doing that in ajaxOptions means it will not be easy to extend that object with the current URL.

I would suggest associating the URL with the element your plugin is enhancing before the AJAX call, using data() or similar.


You could modify the request & settings objects before sending with following code:

$.ajaxSetup({
    beforeSend: function(jqXHR, settings) {
        jqXHR.url = settings.url;
    }
});

Then access xhr.url in the statusCode callback. It should work.


Need Your Help

Firestore query documents startsWith a string

java firebase google-cloud-firestore

Is it possible to query a firestore collection to get all document that starts with a specific string?

Base64 Java encode and decode a string

java base64 decode encode

I want to encode a string into base64 and transfer it through a socket and decode it back. But after decoding it gives different answer. Following is my code and result is "77+9x6s="