Jquery Single Function for all Ajax requests


Sometimes developers use multiple Ajax requests in a webpage. For this they use the same $.ajax() function provided by the jQuery people multiple times in the same page. Here is a function to completely avoid it. Keep this function at the common header or footer and include it whenever you need to call the Ajax.

function callAjax(getdata,callback)
{
    getdata = ((getdata===undefined) ? '' : getdata);
    callback = ((callback===undefined) ? '' : callback);
    $.ajax({
      url: 'ajaxscript.php',
      type: "POST",
      data: getdata,
      success: function(resp) {
        eval(callback+"(resp);");
      }
    });   
}   

Here 'getdata' is the JSON data to be passed to the Ajax and 'callback' is the callback function to be executed once there is a successful return from ajax. You can write backend scripts in the same page 'ajaxscript.php' or you can also pass a parameter in the callAjax() function mentioning the backend script page you want to execute for a particular function call.