Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX - get response body in success and error

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)

like image 572
Ulug'bek Avatar asked Mar 20 '13 07:03

Ulug'bek


People also ask

How can I get success response in Ajax?

In most cases, you will need to specify the success and error callbacks. The success callback will be called after the successful completion of the AJAX call. The response returned by the server will be passed along to the success callback.

How do I return data after Ajax call success?

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });

What is success and error function in Ajax?

Example# success and Error : A success callback that gets invoked upon successful completion of an Ajax request. A failure callback that gets invoked in case there is any error while making the request.


1 Answers

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
          }
    });
like image 116
Arun P Johny Avatar answered Oct 22 '22 22:10

Arun P Johny