4

I've a js which makes $.ajax call, on success of which, I need to do something. Typical implementation would be like:

$.ajax({
    url: "/Sales/Quotations/LinkQuotabtleItemToSites",
    type: "POST",
    success: function (data) {
        // do something
    }
});
The issue is, this js function is developed by another developer and I've dependency on that ajax success call. I was wondering if there is a simple way to subscribe to the success event and handle it in my own js file
Mahesh Kava
  • 773
  • 5
  • 16
  • just want to confirm, it is the only Ajax call you want to hit through out the project? – Ram Singh Oct 23 '15 at 05:21
  • as of now, yes but I don't know in the future if my logic would depend on other ajax calls (business rule change..you see) – Mahesh Kava Oct 23 '15 at 05:24
  • 1
    http://www.binaryintellect.net/articles/749ed588-b408-4a7e-94da-77549c00e803.aspx try to follow the above – Ram Singh Oct 23 '15 at 05:25
  • 2
    "Subscribing" to the success event sounds like a horrible idea. **"so we both are working independently and don't overwrite each others changes"**. I am sure that you **really need** to use [version control](https://en.wikipedia.org/wiki/Version_control). That's how programmers of the whole world work. Please, read these articles: http://stackoverflow.com/questions/1408450/why-should-i-use-version-control and http://stackoverflow.com/questions/2658/getting-started-with-version-control – Yeldar Kurmangaliyev Oct 23 '15 at 05:31
  • Thanks Ram for the link, is it possible to subscribe to a specific call, then having a global call back handler? – Mahesh Kava Oct 23 '15 at 05:33

2 Answers2

5

ajaxSuccess will be your friend for that : https://api.jquery.com/ajaxSuccess/

Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.

$(document).ajaxSuccess(function(event, xhr, settings) {
  console.log('hello !');
});

But with this, you'll listen every ajax success event. So if you need to listen to only one request, you may need to do dhis :

$(document).ajaxSuccess(function(event, xhr, settings) {
  if (settings.url == '/foo/bar/somefile') {
      console.log('hello !');
  }
});
Magus
  • 14,796
  • 3
  • 36
  • 51
0

You may use custom events:

$('.my-link').click(function() {
  $.ajax({
    url: "/Sales/Quotations/LinkQuotabtleItemToSites",
    type: "POST",
    success: function(response) {
      $(document).trigger('mynamespace:mytrigger', [response]);
    }
  });
});

// Developer 1 listens:
$(document).on('mynamespace:mytrigger', function (event, response) {
  console.log('Listener 1 and response is:', response);
});


// Developer 2 listens in some other place:
$(document).on('mynamespace:mytrigger', function (event, response) {
  console.log('Listener 2 and response is:', response);
});
madpoet
  • 1,023
  • 11
  • 28