32

I need to append this div to another div , but it give me this error :

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

This is my javascript code:

var str = {'message': message,'text': text};
$.ajax({
    type: "POST",
    url: "api/reply",
    data: str,
    dataType: "json",
    cache: false,
    success: function(response)
    {
        var respons = jQuery.parseJSON(response);
        var type = respons.status
        if (type == 'success') {
            $("<div></div>").html(respons.message).appendTo("#messages");
        }
        else
        {
            toastr.error(respons.message)
        }
    }
})
FirstOne
  • 6,033
  • 7
  • 26
  • 45
Ðr Ssamade
  • 526
  • 1
  • 6
  • 10
  • 2
    That is not valid JSON. Run it through jsonlint.com to validate it – charlietfl Jul 16 '16 at 15:33
  • When you throw your code into JSBin you immediately see that you have some syntax errors. I added a test API endpoint and a fake input so that you can play with it there: http://jsbin.com/sojibojetu/edit?html,js,output – Andru Jul 16 '16 at 15:42
  • Possible duplicate of [I keep getting "Uncaught SyntaxError: Unexpected token o"](https://stackoverflow.com/questions/8081701/i-keep-getting-uncaught-syntaxerror-unexpected-token-o) – Heretic Monkey Jun 22 '17 at 19:15
  • This is the 'problem' with jquery. In XMLHTTPRequest and Fetch API, we have to perform JSON.parse ourselves, so we are used to doing it; but in case of JQuery, the maker has done the parsing for us. So you simply need to drop the JSON.parse. – Daniel Wu Jan 13 '23 at 05:06

4 Answers4

60

Simply change

var respons = jQuery.parseJSON(response);

to

var respons = response;

Explanation:

If the configuration of your AJAX call is having dataType: json you'll get a JavaScript object so it's no longer necessary to use JSON.parse().

Andreas
  • 5,393
  • 9
  • 44
  • 53
Alfredo EM
  • 2,029
  • 1
  • 14
  • 16
21

This is a hackish and unorthodox way of parsing JSON, but if you still want to use JSON.parse() from an AJAX call or simply on JSON that is already parsed and isn't a string, you can use JSON.stringify() inside it:

var respons = JSON.parse(JSON.stringify(response));
Max Voisard
  • 1,685
  • 1
  • 8
  • 18
6

Problem is you're not parsing a string, you're parsing an already parsed object.

Nalan Madheswaran
  • 10,136
  • 1
  • 57
  • 42
2

the values in your object seem to be undefined. change var str = {'message': message,'text': text}; to var str = {message: 'message',text: 'text'};

Tal
  • 700
  • 4
  • 11