Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get settings used by jquery $.ajax request

I'm using $.ajax for many requests each one has a different settings and values passed to the function.

I need to check whether these settings are merged correctly into $.ajax settings.

var options = {
  endpoint: '/path/page'
  method : "POST",
  mode: 'abort',
  data : { value : $(this).val() },
  headers : { 'X-Key' : 'value' }
}

$.ajax( $.extend(true, {
    url: endpoint,
    type: 'GET',
    cache: true,
    dataType: 'json',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    headers : {
        'X-Same-Domain':'1',
    },
    async: true,
    data: data,
    timeout: 5000,
}, options) )

How can I see in console those settings used by $.ajax request on success or failure?

like image 772
Adriano Rosa Avatar asked Nov 23 '25 01:11

Adriano Rosa


2 Answers

This question is old, but it can help those in need from now on with low complexity. It is possible to decorate the jqxhr with settings in the .ajaxSend, with this it will be passed on to all the flow where the jqxhr is after sending.

$(document).ajaxSend(function (event, jqxhr, settings) {
  jqxhr.settings = settings;
});
like image 149
portella Avatar answered Nov 25 '25 16:11

portella


jQuery doesn't seem to support this but you can implement this yourself:

function ajax(options) {
    var defer = $.Deferred();
    $.ajax(options)
        .done(function(data, textStatus, jqXHR) {
            defer.resolve(data, textStatus, jqXHR, options);
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            defer.reject(jqXHR, textStatus, errorThrown, options);
        });
    return defer.promise();
}

Usage

var options = {
    endpoint: '/path/page'
    method : "POST",
    mode: 'abort',
    data : { value : $(this).val() },
    headers : { 'X-Key' : 'value' }
};

ajax($.extend(true, {
    url: endpoint,
    type: 'GET',
    cache: true,
    dataType: 'json',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    headers : {
        'X-Same-Domain':'1',
    },
    async: true,
    data: data,
    timeout: 5000,
}, options)).done(function(data, textStatus, jqXHR, ajaxOptions) {
    console.log("done", ajaxOptions);
}).fail(function(jqXHR, textStatus, errorThrown, ajaxOptions) {
    console.log("fail", ajaxOptions);
});
like image 37
huysentruitw Avatar answered Nov 25 '25 16:11

huysentruitw