Ðr Ssamade
Ðr Ssamade

Reputation: 576

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

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)
        }
    }
})

Upvotes: 37

Views: 123020

Answers (4)

Alfredo EM
Alfredo EM

Reputation: 2069

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().

Upvotes: 62

Max Voisard
Max Voisard

Reputation: 1942

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));

Upvotes: 24

Nalan Madheswaran
Nalan Madheswaran

Reputation: 10562

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

Upvotes: 7

Tal
Tal

Reputation: 700

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

Upvotes: 2

Related Questions