0

I Know in jQuery ajax there is tools to detect error but that I want is how to describe what is the problem? 404, no internet connection, internal server error or something else?

This is my simple program

<script type="text/javascript" charset="utf-8" src="http://jquery.local/jquery-1.7.2.min.js"></script>

<script>
    function Create_new_event ()
    {
        url = "missing.php";

        $.post(url, {
        }, function(hasil) {
            alert (hasil);
        });
    }

    $(document).ajaxError(function(event, request, settings) {
        // I believe in this area I should put my code to detect problem
    });

</script>

<button onClick="Create_new_event ();">Send</button>
Reinstar
  • 146
  • 1
  • 1
  • 21

3 Answers3

3

Here is an example :

$(document).ajaxError(function(e, x, settings, exception) {
            var message;
            var statusErrorMap = {
                '400' : "Server understood the request but request content was invalid.",
                '401' : "Unauthorised access.",
                '403' : "Forbidden resouce can't be accessed",
                '500' : "Internal Server Error.",
                '503' : "Service Unavailable"
            };
            if (x.status) {
                message =statusErrorMap[x.status];
                                if(!message){
                                      message="Unknow Error \n.";
                                  }
            }else if(exception=='parsererror'){
                message="Error.\nParsing JSON Request failed.";
            }else if(exception=='timeout'){
                message="Request Time out.";
            }else if(exception=='abort'){
                message="Request was aborted by the server";
            }else {
                message="Unknow Error \n.";
            }

            alert(message);
});
sdespont
  • 13,915
  • 9
  • 56
  • 97
1

Yes you can achieve that with thrownError param, do this: http://jsfiddle.net/XJ7L2/

 function Create_new_event() {
   url = "missing.php";

   $.post(url, {}, function (hasil) {
       alert(hasil);
   });
 }
 $(function () {
   $('button').click(function(){
     Create_new_event();
   });
   $(document).ajaxError(function (event, request, settings, thrownError) {
     console.log(request.status  + ' : ' + thrownError);
   });
 });

When an HTTP error occurs, thrownError receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."

Nick
  • 5,995
  • 12
  • 54
  • 78
Jai
  • 74,255
  • 12
  • 74
  • 103
1

If you look at what the request parameter contains (console.log( request );), you'll see that the response code is in request.status and textual description is in request.statusText.

So something like this:

$(document).ajaxError(function(event, request, settings) {
    console.log( 'Server returned '+request.status+': '+request.statusText );
});

Demo: http://jsfiddle.net/FSfEh/

JJJ
  • 32,902
  • 20
  • 89
  • 102