Organizational Research By

Surprising Reserch Topic

how to get the jquery ajax error response text


how to get the jquery ajax error response text  using -'php,javascript,jquery,ajax,error-handling'

I am sending an error response to my jQuery.
However, I can not get the response text (in the example below this would be Gone to the beach)

The only thing jQuery says is 'error'.

See this example for details:

php

<?
    header('HTTP/1.1 500 Internal Server Error');
    print "Gone to the beach"
?>


jQuery

$.ajax({
    type:     "post",
    data:     {id: 0},
    cache:    false,
    url:      "doIt.php",
    dataType: "text",
    error: function (request, error) {
        console.log(arguments);
        alert(" Can't do because: " + error);
    },
    success: function () {
        alert(" Done ! ");
    }
});


Now my result ist:

log:

 [XMLHttpRequest readyState=4 status=500, "error", undefined]


alert:


  Can't do because: error


Any ideas?
    

asked Sep 21, 2015 by dahiyabecomp
0 votes
11 views



Related Hot Questions

4 Answers

0 votes

Try:

error: function(xhr, status, error) {
  var err = eval("(" + xhr.responseText + ")");
  alert(err.Message);
}

Look also at this encosia article for proper error handling.

answered Sep 21, 2015 by ukohale
0 votes

you can try it too:

$(document).ajaxError(
    function (event, jqXHR, ajaxSettings, thrownError) {
        alert('[event:' + event + '], [jqXHR:' + jqXHR + '], [ajaxSettings:' + ajaxSettings + '], [thrownError:' + thrownError + '])');
    });
answered Sep 21, 2015 by suyesh.lokhande
0 votes

This is what worked for me

    function showErrorMessage(xhr, status, error) {
        if (xhr.responseText != "") {

            var jsonResponseText = $.parseJSON(xhr.responseText);
            var jsonResponseStatus = '';
            var message = '';
            $.each(jsonResponseText, function(name, val) {
                if (name == "ResponseStatus") {
                    jsonResponseStatus = $.parseJSON(JSON.stringify(val));
                     $.each(jsonResponseStatus, function(name2, val2) {
                         if (name2 == "Message") {
                             message = val2;
                         }
                     });
                }
            });

            alert(message);
        }
    }
answered Sep 21, 2015 by rajeevr642
0 votes

If you're not having a network error, and wanting to surface an error from the backend, for exmple insufficient privileges, server your response with a 200 and an error message. Then in your success handler check data.status == 'error'

answered Sep 21, 2015 by balvant maurya

...