8

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

AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

5 Answers5

24
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.
});
N.B.
  • 13,688
  • 3
  • 45
  • 55
3

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");
});
jessegavin
  • 74,067
  • 28
  • 136
  • 164
1
function loadProjects(pID, callback) {

    $.ajax({
        url: myURL,
        success: function (dataJS) { if (callback) { callback(); } }
    });

}

Invoking something like this:

loadProjects(111, function() { alert('hello!'); });
mVChr
  • 49,587
  • 11
  • 107
  • 104
1

You can pass a function to another function as if it were any other object. Check this out:

function loadProjects(pId, callback) {

  $.ajax({
    url: myUrl,
    success: function() {
      callback.call(); // <-- invokes your callback with no args
    }

}

You might also read up on the MDC documentation (function.call()).

ninjascript
  • 1,751
  • 1
  • 10
  • 8
-1
function loadProjects(pID, callback) {
  $.ajax({
    url: myURL,
    success: function (dataJS) {
      // your initial method declaration goes here
      ...

      // just call the callback method at the end of the success method
      callback();
    }
matt
  • 9,113
  • 3
  • 44
  • 46