13

I have the following code :

$("#loginSubmitButton").on("click",function(){
  var loginUserDetails = {
    email: $("#email").val(),
    password: $("#password").val()
  };

  //Send the AJAX request to authenticate the user
  $.ajax({
    type: "POST",
    url: "/somewebservice/v1/users/authenticate",
    data: JSON.stringify(loginUserDetails),
    contentType: "application/json;charset=UTF-8",
    dataType: "json",
  }).done(function() {
      $("#loginResult").text("Login successful");
    })
    .fail(function() {
      $("#loginResult").text("Login failed");
    });

});

As per the jquery documentation (unless I am understanding something incorrectly) I expect the done to be fired if I receive a 200 OK from my web server. However, in chrome console I can see a 200 OK response but jquery seems to fire the fail handler.

Does anyone have any idea what I might be doing wrong here?

m59
  • 43,214
  • 14
  • 119
  • 136
tsure
  • 315
  • 3
  • 6
  • 16

6 Answers6

34

You need to remove:

dataType: "json"

user2597843
  • 379
  • 3
  • 7
28

There are lots of suggestions to remove

dataType: "json"

While I grant that this works it's probably ignoring the underlying issue. It's most likely caused by a parser error (the browser parsing the json response). Firstly examine the XHR parameter in either .always() or .fail().

Assuming it is a parser fail then why? Perhaps the return string isn't JSON. Or it could be errant whitespace at the start of the response. Consider having a look at it in fiddler. Mine looked like this:

Connection: Keep-Alive
Content-Type: application/json; charset=utf-8

{"type":"scan","data":{"image":".\/output\/ou...

In my case this was a problem with PHP spewing out unwanted characters (in this case UTF file BOMs). Once I removed these it fixed the problem while also keeping

dataType: json
Sam Strachan
  • 525
  • 5
  • 8
  • 4
    Awesome! Removing the `dataType` is just a workaround. Fixing the data source is the real fix. – Gustavo Straube Jun 23 '16 at 21:17
  • Nice. I think the issue with mine was that the server was returning `text/html` rather than a JSON response. – harvzor Jul 22 '17 at 21:56
  • The real answer. In my case I had an equation that was returning `INF` (I didn't even know this constant existed) and that was causing a json parse error. – Gavin Oct 14 '19 at 06:03
8

If your server returns empty string for a json response (even if with a 200 OK), jQuery treats it as failed. Since v1.9, an empty string is considered invalid json.

Whatever is the cause, a good place to look at is the 'data' parameter passed to the callbacks:

$.ajax( .. ).always(function(data) {
    console.log(JSON.stringify(data));
});

Its contents will give you an understanding of what's wrong.

Can Bayburt
  • 120
  • 1
  • 3
3

Need to remove , from dataType: "json",

 dataType: "json"
Bhupendra
  • 248
  • 2
  • 7
1

The ajax URL must be the same domain. You can't use AJAX to access cross-domain scripts. This is because of the Same Origin Policy.
add "dataType:JSONP" to achieve cross domain communication

use below code

 $.ajax({
       URL: cross domain 

        dataType: 'jsonp'  
            // must use dataType:JSONP to achieve cross domain communication, otherwise done function would not called. 
           // jquery ajax will return "statustext error" at }).always(function(data){}


 }).always(function(data){
      alert(JSON.stringify(data));
   }
hoogw
  • 4,982
  • 1
  • 37
  • 33
0

A few things that should clear up your issue and a couple hints in general.

  1. Don't listen for a click on a submit button. You should wait for the submit event on the form.

  2. The data option for $.ajax isn't expecting a JSON string. It wants a serialized string or an array with name and value objects. You can create either of those easily with .serialize() or .serializeArray().

Here is what I was thinking for your script.

$('#form-with-loginSubmitButton').on('submit', function(e){


  e.preventDefault():

  var $form = $(this),
      data = $form.serializeArray();

  $.ajax({
    type: "POST",
    url: "/somewebservice/v1/users/authenticate",
    data: data
  }).done(function(result){
    console.log(result);
  });

});
Bill Criswell
  • 32,161
  • 7
  • 75
  • 66
  • Any reason why I shouldn't listen for a click event? My web service expects a POST with JSON params and so I used JSON.Stringify. Is that a problem? – tsure Dec 16 '13 at 02:53
  • You can submit a form without clicking, or "click" a button without clicking. The browser might cover up for those issues in some cases but I wouldn't rely on it. – Bill Criswell Dec 16 '13 at 15:09