0

I am using the following style of AJAX calls:

$.ajax({
    dataType: "json",
    type: "GET",
    url: url
}).done(function(result, textStatus, jqXHR) {
    if(result.success == 1) {
        try {
            if(!result.value_that_might_be_null) {
                throw new Error("Value is null");
            }
        } catch(err) {
            ajaxError(jqXHR, err.message);
        }

    } else {
        throw new Error("Unsuccessful");
    }
}).fail(ajaxError);

function ajaxError(jqXHR, textStatus, errorThrown) {
    console.log('jqXHR: ' + jqXHR);
    console.log('status: ' + textStatus);
    console.log('error: ' + errorThrown);
}

This allows me to have good control over my AJAX calls and can test for certain values not being present, being set to the wrong thing etc.

But, I have a few different AJAX calls, each doing quite different things in the .done() callback, meaning they do need to be separate and not re-factored into a class.

But my problem is, how can I add extra parameters to ajaxError() when its called via the try/catch statement?

Can I just do something like:

function ajaxError(jqXHR, status, error, additionalParameter = null) {
    //blah blah blah
}

ajaxError(jqXHR, errorMessage, errorThrown, myAdditionalParameter);
Mr Pablo
  • 4,109
  • 8
  • 51
  • 104
  • Possible duplicate of [Get more information from a failed jqXHR request](http://stackoverflow.com/questions/26518699/get-more-information-from-a-failed-jquery-jqxhr-request) – pistou Nov 05 '15 at 10:00

1 Answers1

0

You can create a function that accepts success and error callbacks like the following:

function sendRequest(url, success, error) {
  $.ajax({
    dataType: "json",
    type: "GET",
    url: url,
    success: function(result, textStatus, jqXHR) {
      // do something if you want to
      if (success)
        success();
    },
    error: function(jqXHR, textStatus, errorThrown) {
      // do something if you want to
      if (error)
        error();
    }
  });
}

function ajaxError(jqXHR, textStatus, errorThrown) {
  console.log('jqXHR: ' + jqXHR);
  console.log('status: ' + textStatus);
  console.log('error: ' + errorThrown);
}

which you can call like sendRequest('/url',null,ajaxError) or sendRequest('/url',null,ajaxError.bind(null,someParameter))

T J
  • 42,762
  • 13
  • 83
  • 138
  • "ajaxError.bind(null,someParameter)" is the key here right? – Mr Pablo Nov 05 '15 at 10:25
  • @MrPablo yes look into [bind](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind) method hope you already did – T J Nov 05 '15 at 13:43
  • I actually ended up using beforeSend and adding a custom property to the jqXHR object, so I can spot which AJAX call was fired – Mr Pablo Nov 05 '15 at 14:19