jQuery Custom Ajax With Wrapper Layer

January 15, 2010

Whilst working on our online game Street Crime - Mmorpg Gangster Game I came accross the need to add a wrapper layer to all of our ajax calls thus to make sure players are always logged in before they make the call and if not then re-direct them too our login pages.

Most of you who are familiar with jQuery will also be familiar with the $.ajax() function that is commonly used for making ajax requests.

I decided to use jQuerys plugin functionality to create the wrapper layer.

jQuery.AJAXwrapper=function(options) {
var defaults = {
extensions: '',
theurl: '',
thetype: "POST",
defaultdataType: "xml",
payload: ''
var options = $.extend(defaults, options);
url: options.theurl,
type: options.thetype,
data: options.extensions,
dataType: options.defaultdataType,
beforeSend: function(){
//in here insert your custom function
success: function(xml){
if(typeof options.payload==='function'){

I call my function above by using a simple bit of code that you can added to any action/event you like.

theurl: "somephp.php",
extensions: "action=refresh",
payload: yourcustomfunction;

And finally I stick an alert in the custom function I have selected to be my on success from the AJAXwrapper function.

function yourcustomfunction(){
alert("we made it to this bit");

There you have it now you could make all of your ajax calls using AJAXwrapper({}) and its possible values which I have listed below for clarity.

  • extensions - These are your normal 'data' fields in the normal $.ajax() function so something like 'action=fred'
  • theurl - Quite simply the url you want AJAXwrapper to call
  • thetype - The type of request your making GET,POST default is set to POST
  • defaultdataType - The default data type of the call my function is defaulted to xml, but you could choose JSON,HTML etc
  • payload - Finally the payload, this is your defined function for AJAXwrapper to call when your request comes back successfully.

About me

Hello! I'm David Heward, how are you going? I'm a Senior Devops/Build Engineer, specialising in AWS & Cloud Automation. Based in London. Strong 10+ year background in Software development. Have a read of my blog. Have a look at some of my working projects. Contact me at @davehewy or on Linkedin.