Home Unexpeced token error when setting contentType to application/json
Reply: 1

Unexpeced token error when setting contentType to application/json

b11 Published in 2017-12-07 02:13:13Z

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

    url: url,
    method: "POST",
    data: data,
    contentType: 'application/json',
    dataType: 'json',
    beforeSend: function (xhr) {
        xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
    success: function (success) {
charlietfl Reply to 2017-12-07 02:27:20Z

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

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.300163 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO