I have the following function:
function loadProjects(pID) {
    $.ajax({
        url: myURL,
        success: function (dataJS) {XXXXXXXXXXXXXXXX}
    });
}
I call this function like so loadProjects(1);
Issue is I want to be able to define a callBack function after success, and I'd like to include it when I do loadProjects(1, callback:{whatever js is included here gets called back after success})
How can I have a function accept a callback? How can I pass a callback to that function?
Thanks
function loadProjects(pID, callbackFunction)
{
    $.ajax({
        url: myURL,
        success: function (dataJS)
        {
            if(typeof callbackFunction == 'function')
            {
                callbackFunction.call(this, dataJS);
            }
        }
    });
}
Usage:
loadProjects(pID, function(dataJS)
{
    // do stuff with your dataJS, bear in mind you can call the parameter any name.
});
                        Here's how you can modify your function so that it can accept a callback.
function loadProjects(pID, callback) {
    $.ajax({
        url: myURL,
        success: function (dataJS) {
          if ($.isFunction(callback)) {
            callback.call();
          }
        }
    });
}
Here's how you would use it.
function myCoolCallback() {
  alert("I am cool");
}  
loadProjects(123, myCoolCallback);
Or you can use it with an anonymous function like so.
loadProjects(123, function() {
  alert("I am cool");
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With