6

Is there any way to intercept an ajax request being made via jquery, to insert additional variables into it?

I know that .ajaxStart() lets you register a callback which triggers an event whenever an ajax request begins, but what I'm looking for is a way to cancel that ajax request if it meets certain criteria (e.g url), insert some more variables into its content, and then submit it.

This is for a plugin for a 3rd party software whose own code can't be changed directly.

Edit: Seems like .ajaxSetup() lets you set some global variables related to ajaxRequests. If I registered a beforeSend function, would that function be able to cancel the request to make a different one on meeting certain criteria?

Ali
  • 261,656
  • 265
  • 575
  • 769
  • have you tried just returning `false`? That works to stop a lot of events, though I don't know specifically if it works for this one. or `event.preventDefault()`? – Colleen Dec 28 '12 at 00:54
  • Interesting, I'll try event.preventDefault.. – Ali Dec 28 '12 at 00:55
  • possible duplicate of [How to stop ajax request](http://stackoverflow.com/questions/9374305/how-to-stop-ajax-request) – Travis J Dec 28 '12 at 00:58
  • Nope, no luck with preventdefault or returning false with ajaxStart – Ali Dec 28 '12 at 00:59
  • 1
    Not a duplicate since in that question you had control over when the ajax request starts and could assign additional variables to it, etc, but in my case i have no control over this code and can only try to impact it from outside. – Ali Dec 28 '12 at 01:00

1 Answers1

10

Figured it out, this was the code I used:

jQuery(document).ready(function()
{    
    var func = function(e, data) 
    {       
        //data.data is a string with &seperated values, e.g a=b&c=d&.. . 
        //Append additional variables to it and they'll be submitted with the request:      
        data.data += "&id=3&d=f&z=y";
        return true;
    };
    jQuery.ajaxSetup( {beforeSend: func} );
    jQuery.post('example.php', {a : 'b'}, 'json');    
} );

To cancel the request, returning false from func seemed to work.

Ali
  • 261,656
  • 265
  • 575
  • 769