3

I'm looking for a way to fire an event when a POST Ajax call completes and perform some action on returned data from outside any script/plugin without modifying any POST callbacks code too. See pseudo code:

$.post(url, {id: 3,...}, function( d ) {
    ...some js code here
});

//Looking for an event like this :
$(document).on('post', '??' ,function() {
    //I want access to 'd' from post callback in here, and any other POST calls return data...
}
Graben
  • 202
  • 3
  • 8
  • http://api.jquery.com/jQuery.ajax/ – LouisK Jul 11 '15 at 00:17
  • You may want to look into adding an event listener to XMLHttpRequest. See: http://stackoverflow.com/questions/25335648/how-to-intercept-all-ajax-requests-made-by-different-js-libraries – leemac Jul 11 '15 at 00:18
  • so putting a callback in .success() would not be suitable...? – trickpatty Jul 11 '15 at 00:22
  • I want some common operations to all ajax responses in my app to be pushed by server side, so listening to post data returned and executing an event on that seems the best way to achieve that without modifying all post callback functions in an application.... – Graben Jul 11 '15 at 01:30

2 Answers2

2

Try utilizing .ajaxComplete()

$(document).ajaxComplete(function(event, jqxhr, settings) {
  // I want access to 'd' from post callback in here, 
  // and any other POST calls return data...

  // do stuff when `$.post()` completes
  console.log(jqxhr.responseText); // `d`
});

$.post(url, {id: 3,...}, function( d ) {
 // do stuff
 // ...some js code here
});
guest271314
  • 1
  • 15
  • 104
  • 177
  • Thank you very much, I did not know about that jquery function ! Exactly what I was looking for ! – Graben Jul 11 '15 at 01:35
0

Not sure why you wouldn't use success: attribute of $.post or .done(function() {}).

To answer your actual question though: in the callback of $.post:

$.post(url,{...},function( d ) {
    $(document).trigger('custom:postdone',[d]);
});

Access with:

$(document).on('custom:postdone',function(event, d) {
    //...manipulate d...
});

See for more: https://learn.jquery.com/events/introduction-to-custom-events/

Michael Tallino
  • 821
  • 4
  • 16
  • 1
    That is not what I am looking for, as I specified "without modifying any POST callbacks code too". The trigger is inside post callback lambda function, which is not something I can modify. – Graben Jul 11 '15 at 01:26