Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ajax - global settings. Is it possible to know what event/element trigger the ajax call?

Tags:

jquery

ajax

This is easy enough to work around, but it would be nice if it was wrapped up in the global ajax setup

When I run an ajax call, I'd like to know which element/event trigger the ajax call in the beforeSend option.

Is there a concise way of doing this?

like image 642
recursive_acronym Avatar asked Oct 18 '11 18:10

recursive_acronym


1 Answers

The beforeSend callback takes two arguments: the XMLHTTPRequest instance and the settings used by the current AJAX call.

Therefore, if you pass the triggering element and event in the context option, they will be available to beforeSend even if you define it in the global setup:

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        var element = settings.context.element;
        var event = settings.context.event;

        // Do something with 'element' and 'event'...
    }
});

$("selector").click(function(e) {
    $.ajax("url", {
        // your settings,
        context: {
            element: this,
            event: e
        }
    });
});
like image 159
Frédéric Hamidi Avatar answered Oct 31 '22 15:10

Frédéric Hamidi