jqueryajaxerror-handling

Debugging jQuery ajax function


JS code:

$.ajax({
        type: 'POST',
         url: 'http://localhost/MyServiceDir/Service.asmx/Foo',
         contentType: 'application/json; charset=utf-8',
         data: jsonData,
         success: function (msg) {
             alert("good");
         },
         error: function (xhr, status) {
              switch (status) {
                 case 404:
                     alert('File not found');
                     break;
                 case 500:
                     alert('Server error');
                     break;
                 case 0:
                     alert('Request aborted');
                     break;
                 default:
                     alert('Unknown error ' + status);
             } 
         }
     });

I get "unknown error error". How do I get to the bottom of this? I would like to know what the error actually is.


Solution

  • The "status" parameter only includes why it failed -- timeout, error, etc... To get the status code you need to check the response object: xhr.status

    See http://www.w3.org/TR/XMLHttpRequest/#response for details.

    If you are getting "500 Internal Server Error" that is all you are going to get from ajax. You will have to check your application or server logs. This could be a syntax error or or library error or something else along those lines.