Nicholas Chew Nicholas Chew - 2 months ago 7
Ajax Question

Ajax to call another Ajax function upon done

var App = {
actionRequest: function (url,data,callback){
$('#menu').panel('close');
$.mobile.loading('show');
$.when(

$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
})

).done(function(data,html) {
callback ?
$.mobile.loading('hide');
}

);
}

refreshCart: function(){
App.loadExternalContent('content','scripts/data_ajax.php','action=getCart','temp

lates/cart.htm');
}
}


I need to call refreshCart in ".done". How can i write a callback function in ".done" to do so? Sorry i am new with Ajax.

Answer
var object = {
  actionRequest: function(url, data, callback) {
    $('#menu').panel('close');
    $.mobile.loading('show');
    $.when(

      $.ajax({
        method: 'POST',
        url: url + '?' + new Date().getTime(),
        data: data
      })

    ).done(function(data, html) {
        if ($.isFunction(callback)) {
          callback();
        }
        $.mobile.loading('hide');
      }

    );
  }
}

usage:

if refreshCart is function in the object you can also do this:

var object = {
  actionRequest: function(url, data, callback) {
    var that = this;

    $('#menu').panel('close');
    $.mobile.loading('show');
    $.when(

      $.ajax({
        method: 'POST',
        url: url + '?' + new Date().getTime(),
        data: data
      })

    ).done(function(data, html) {
        // without using a callback
        that.refreshCart();
        $.mobile.loading('hide');
      }

    );
  },
  refreshCart: function() {
    App.loadExternalContent('content', 'scripts/data_ajax.php', 'action=getCart', 'templates/cart.htm');
  }
}