AJAX - get response body in success and error

Ulug'bek Ro'zimboyev picture Ulug'bek Ro'zimboyev · Mar 20, 2013 · Viewed 40.2k times · Source

I am apologize for the stupid question, but I need your help. I need to get information about response inside AJAX.

$.ajax({
          type: "POST",
          url: '/register',
          data : registerRequestJSON,
          contentType:"application/json",
          success: function(data){
              $("#register_area").text();// need to show success
          },
          error: function(err) {
            $("#register_area").text("@text"); // @text = response error, it is will be errors: 324, 500, 404 or anythings else
          }
    });

How can I use response body? (documentation Jquary.Ajax is not working at the momment)

Answer

Arun P Johny picture Arun P Johny · Mar 20, 2013

The first param to error handler is jqxhr, it has the property responseText which will give the response body.

$.ajax({
          type: "POST",
          url: '/register',
          data : registerRequestJSON,
          contentType:"application/json",
          success: function(data){
              $("#register_area").text();// need to show success
          },
          error: function(jqxhr) {
            $("#register_area").text(jqxhr.responseText); // @text = response error, it is will be errors: 324, 500, 404 or anythings else
          }
    });