Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax call fires error event but returns 200 ok

$.ajax({
        url: 'http://intern-dev01:50231/api/language',
        type: 'GET',
        dataType: 'json',
        success: function() {
            console.log('It Works!');
        },
        error: function (request,status, error) {
            console.log(error);
            alert(status);
        }
    });

Why do this ajax call not work ?? if i call in browser it works fine :/.

This is what fiddler returns:

HTTP/1.1 200 OK
Content-Length: 122
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 26 Apr 2013 06:56:40 GMT

[{"LanguageId":1,"LanguageName":"Dansk"},{"LanguageId":2,"LanguageName":"Tysk"},{"LanguageId":3,"LanguageName":"Engelsk"}]
like image 430
user2314110 Avatar asked Apr 26 '13 07:04

user2314110


People also ask

How can ajax call error be resolved?

The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.

What triggers ajax error?

Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the .ajaxError() method are executed at this time. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.


2 Answers

You have to check ajax response if it is valid or not. When you specify in ajax:

dataType: 'json',

jQuery will fire the error event if the response cannot be parsed as JSON, even if server returns 200 OK. Check the data returned from the server and make sure it is valid JSON (try JSONLint service).

If the returned data is not JSON or it has syntax errors then fix them in your server side code. You can just return {} from the server side script.

Also try this.

$.ajax({
    url: 'http://intern-dev01:50231/api/language',
    type: 'GET',
    cache: false,        
    complete: function (xhr, status) {
      if (status === 'error' || !xhr.responseText) {
          console.log(error);
          alert(status);
      }
      else {
       console.log('It Works!');.
      }
    }        
});
like image 155
Bharat Chodvadiya Avatar answered Oct 12 '22 05:10

Bharat Chodvadiya


There is a parsing error since the status shows 200 OK. The problem lies in the datatype:json. To test this, remove the line and it should work. In order to fix this, you can change it to the datatype:text. See this link too for similar question

like image 33
SanTheta Avatar answered Oct 12 '22 04:10

SanTheta