Reputation: 67
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");
}
});
Upvotes: 0
Views: 394
Reputation: 171690
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
Upvotes: 1