Last Updated: February 25, 2016
·
391
· ekidd

Easy Async Ajax Calls

Use this whenever you have functions that need to wait on data returned from your ajax calls.

Define these functions in whatever namespace you need to access them from

function sendData(sendObj) {
  return jQuery.ajax({
    url: sendObj.url,
    dataType: sendObj.dataType,
    data: sendObj.data,
    type: sendObj.type
    //you can define as much or as few ajax settings as you want
  });
}

function response(f,success,error) {
  //set success function
  f.success(function(returnedData){
    success(returnedData);
  });
  //set error function
  f.error(function(returnedData){
    error(returnedData);
  });
}

When you are ready to call to the server, define your sendObj and your response functions:

var sendObj ={};
sendObj.url = 'example.com/ajax.php';
sendObj.dataType = 'json';
sendObj.data = {fruit: 'apple', veggie: 'carrot'};
sendObj.type = 'POST';

var produceSuccess = function(data){
  if(data) {
    //It worked! Do stuff with data!
  }
}

var produceError = function(data){
  if(data) {
    //Fail!
  }
}

Then you call your functions like so:

callback = sendData(sendObj);
response(callback,produceSuccess,produceError);

Now whatever needs to happen when your calls complete will wait for the data they need - no need to redefine the ajax functions every time!