Search code examples
javascriptajaxposthttp-status-code-400

Client submitted invalid JSON: lexical error: invalid string in json text.↵


I have an ajax POST method that, despite what I am sending to the server, is apparently appending a '↵' character to the value field. My code:

$.ajax({
   url: url,
   type: "POST",
   data: {"name" : "lol"},
   dataType : "json",
   contentType : "application/json; charset=utf-8"
});

The error returned is error code 400 "Client submitted invalid JSON: lexical error: invalid string in json text.↵" and the console reports that this name=lol↵ is the data being sent.


Solution

  • I just read the error message again and checked with the docs here.

    What you need to do is to send your request in JSON format, not as form-data. You specified the right contentType, but you need to convert your data using JSON.stringify

    Look at this answer here for a possible solution. In your case it would be something like this:

    $.ajax({
        url: url,
        type: 'POST',
        data: JSON.stringify({
            name: 'lol',
        }),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
    });
    

    I hope that works for you. If this didn't work either, I would check with the docs at dev.groupme.com. Maybe you have misspelled some of the JSON fields?