Jquery: Common place to modify all the ajax request

A lot of time we have to add some common parameter in request header or need to include some parameter in request body or query string. Jquery gives us the flexibility to the same using ajaxSetup method

$.ajaxSetup({
	// Define a global before request send
	beforeSend: function(xhr, settings) {
		if (settings.contentType) {
			//Update the query string to append useridentifier
			settings.data = (settings.data || "") + (settings.data ? "&" : "") + "useridentifier="+window.userIdentifier;
			
			//set the header Content-Type
			xhr.setRequestHeader("Content-type", settings.contentType);
		}
		return true;
	}
});

The above piece of code will append few things with every request body and add the request header with that.

Leave a Reply

Your email address will not be published. Required fields are marked *