YPCrumble YPCrumble - 5 months ago 19
jQuery Question

Is it possible to use a global AJAX listener to get the source of the AJAX call?

See this fiddle.

If I have the following code:

HTML :

<div class="button-wrapper">
<button id='firstButton'>
first button
</button>
<button id='secondButton'>
second button
</button>
</div>


JS :

$("button").click(function(event) {
var targetId = event.target.id;
$.ajax({
type: "GET",
url: "https://fiddle.jshell.net",
success: function(data) {
alert('target id is: ' + targetId);
}
});
});

// Is it possible for this to work the same as the above somehow?
$(document).ajaxSuccess(function(event, xhr, ajaxOptions, data) {
var targetId = event.target.id; // Event.target is `document` so does not work
alert('target id is: ' + targetId); // I want this to be the same alert as above.
});


Is it possible to pass the id of the button firing an AJAX call to a global listener (
$(document).ajaxSuccess
)?

Answer

Sure, pass it along with the ajax options, then pull it from the ajax options.

http://jsfiddle.net/tsmknfr2/6

$("button").click(function(e) {
  var targetId = event.target.id;
  $.ajax({
    type: "GET",
    url: "https://fiddle.jshell.net",
    success: function(data) {
        alert('target id is: ' + targetId);
    },
    foop: targetId
  });
});

// Is it possible for this to work the same as the above somehow?
$(document).ajaxSuccess(function(event, xhr, ajaxOptions, data) {
  var targetId = ajaxOptions.foop; 
  alert('target id is: ' + targetId); 
});