Search code examples
javascriptjqueryjsonxmlhttprequest

Jquery / JSON handle XHR Response


I am posting some JSON info using the code below. Currently, if it is successful (200 response) the alert pops up, but if it is unsuccessful nothing happens.

What I would like to do is basically say if successful do X, else do Y.

I have try using an if / else statement within the function, but it doesn't seem to work.

Apologies if this is a silly question, I am new to working with JSON, XHR etc. Any assistance would be greatly appreciated.

jQuery["postJSON"] = function(url, data, callback) {
  if (jQuery.isFunction(data)) {
    callback = data;
    data = undefined;
  }
  return jQuery.ajax({
    url: url,
    type: "POST",
    crossDomain: true,
    contentType: "application/json",
    data: JSON.stringify(data),
    success: callback
  });
};

$.postJSON(
  "https://test.com",
  data,
  function(data, status, xhr) {
    alert("Success");
  }
);

EDIT: Working Code:

jQuery["postJSON"] = function(url, data, callback) {
  if (jQuery.isFunction(data)) {
    callback = data;
    data = undefined;
  }
  return jQuery.ajax({
    url: url,
    type: "POST",
    crossDomain: true,
    contentType: "application/json",
    data: JSON.stringify(data),
    success: callback,
    error: function(xhr, ajaxOptions, thrownError){
    alert(thrownError);
  });
};

$.postJSON(
  "https://test.com",
  data,
  function(data, status, xhr) {
    alert("Success");
  }
);

Solution

  • add this line to your return jQuery.ajax({}) function:

            error: function(xhr, ajaxOptions, thrownError){
            window.alert(thrownError);
        }
    

    hope this helps~