pass optional function as parameter to another function-Collection of common programming errors

Options of how I want to call a function:

myAjax("http://ajaxurl.com", { prop: val }, function(resp) { alert(resp); });

or

function handleSuccess(resp) { alert(resp); }
myAjax("http://ajaxurl.com", { prop: val }, handleSuccess);

or

myAjax("http://ajaxurl.com", { prop: val }, null);

or

myAjax("http://ajaxurl.com", { prop: val }); // param not even provided

How can I handle this on the myAjax function definition? Something like this…?

function myAjax(url, jsonData, successFunc) {
  $.ajax({
    ... all the necessary ajax stuff that normally goes here
    , success: function(response) {
      // custom myAjax success handling goes here. this must happen before optionally-passed-in successFunc gets executed

      // what goes here? this?
      if (typeof successFunc != 'undefined' && successFunc != null) {
        successFunc(response);
      }
    }
  });
}

I tried something like the above, but, it did not call the success function. Do I need to check if successFunc is a function?

Thanks!

  1. Instead of testing against unknown types, verify that the function is indeed a function:

    if (typeof successFunc == 'function') {
        successFunc(response);
    }
    

    Your current code does not prevent successFunc from being run, though. Make sure that the AJAX request is successfully handled (no errors no cross-domain restrictions).

    Since your code doesn’t event reach the point of calling successFunc, it’s likely that an error is generated before if (typeof ....

  2. Testing that the typeof successFunc is “function” will do the trick:

    function myAjax(url, jsonData, successFunc) {
      $.ajax({
        ... all the necessary ajax stuff that normally goes here
        , success: function(response) {
          // custom myAjax success handling goes here. this must happen before optionally-passed-in successFunc gets executed
    
          // what goes here? this?
          if (typeof successFunc === 'function') {
            successFunc(response);
          }
        }
      });
    }
    

Originally posted 2013-11-09 19:42:11.