2

I've got 3-4 ajax calls that will be made at some point. For one of those calls I'd like to trigger a function on the ajaxSend event which is global. This specific ajax call is not necesserily the first or last one in the sequence. It seems that if I attach the ajaxSend event to the $(document), my function will fire every other time that an ajaxSend event occurs. Here's what my code looks like:

//ajax call one $.ajax({ type: "POST", url: myUrl, data: myData }); //ajax call two <- let's say I'd like to fire ajaxSpecificFunc() here $.ajax({ type: "POST", url: myUrl, data: myData }); //ajax call three $.ajax({ type: "POST", url: myUrl, data: myData }); function ajaxSpecificFunc(){ $(document).on("ajaxSend", function() { //Some code that should only happen on ajaxSend but for only one ajax call }); } 

EDIT: I am aware of global:false property for ajax, but do not wish to use it, as this would mean I would have to modify every new ajax call in the future to have ajaxSpecificFunc() continue to fire for the one specific ajax call

2
  • Why not just add the ajaxSpecificFunc into the always or beforeSend callback for your specific AJAX call? Commented Dec 15, 2015 at 10:42
  • You have to bind global ajax method for all requests and filter it out to use it for only specific request regarding which specific data/url/ajax option your are passing to this request. Now if all your ajax requests are similar like supposes your posted code, this wouldn't make sense anyway... Commented Dec 15, 2015 at 10:47

2 Answers 2

2

You can add beforeSend in jQuery.ajax():

$.ajax({ type: "POST", url: myUrl, data: myData, beforeSend: ajaxSpecificFunc }); 

As noted by A.Wolff, this way if we call this function it will bind the ajaxsend for each call. Instead you can remove it and just do the specific ones like:

function ajaxSpecificFunc(jqXHR, settings){ // you can work with the jqXhr and settings } 
Sign up to request clarification or add additional context in comments.

2 Comments

You will bind event on each call and anyway, i'm quite sure it would be to late for the first one
@A.Wolff you picked it up.
2

If you can't bind the handler directly to the ajax call, and want to use the global handlers only then you can check the setting object to see whether the ajax call is your targeted on and if so then call your stuff

$(document).ajaxSend(function(event, jqXHR, settings) { console.log('send', settings); if (settings.url == 'myurl') { //then do your stuff } }) 

Note: But this might become an overkill, and you should try to do it specific to your ajax call

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.