Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercepting a Jquery AJAX request to insert additional variables?

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?

like image 577
Ali Avatar asked Dec 28 '12 00:12

Ali


1 Answers

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.

like image 70
Ali Avatar answered Oct 12 '22 05:10

Ali