jQuery Custom Ajax With Wrapper Layer

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);
$.ajax({
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'){
options.payload(xml);
}
}
});
};

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

$(document).ready(function(){
$("#myid").click(function(){
AJAXwrapper({
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.