Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery statusCode 404 - how to get jqXhr url?

Tags:

jquery

ajax

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;

                        }
                    }
            }
}
like image 774
Nathan Avatar asked Jul 13 '12 08:07

Nathan


2 Answers

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.

like image 179
janlay Avatar answered Oct 22 '22 02:10

janlay


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.

like image 24
Frédéric Hamidi Avatar answered Oct 22 '22 02:10

Frédéric Hamidi