0

I am sending data using AJAX POST. The data is JSON format. See below. However, I keep getting 'Unexpected token u in JSON at position 0'. Why is this happening? The reason I am setting contentType here is so that the Boolean field checked does not get converted to string.

var data = { "user": "tom", "number": 9, "checked": false } $.ajax({ url: url, method: "POST", data: data, contentType: 'application/json', dataType: 'json', beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password)); }, success: function (success) { console.log("success"); } }); 
2
  • where do you get the error? When the javascript runs or when you recieve the answer? Commented Dec 7, 2017 at 2:17
  • @LioraHaydont previously I did not have contentType: 'application/json' and the backend is treating the Boolean like a string, so I read that I should set it to avoid this issue. Which I did, and now it won't even get sent to the backend server Commented Dec 7, 2017 at 2:19

1 Answer 1

1

When you use contentType: 'application/json', you need to stringify the data yourself:

data: JSON.stringify(data), 

As for the error that seems like a response problem. Inspect the actual request in browser dev tools network and see what is actually contained in the reponse body

Sign up to request clarification or add additional context in comments.

1 Comment

The quoted error would be happening server side (and perhaps then included in the response), because the server is receiving the data as user=tom&number=9&checked=false so the first character in the request body is the "u" from "user" and obviously that can't be parsed as JSON.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.