Reputation: 576
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
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
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
Reputation: 10562
Problem is you're not parsing a string, you're parsing an already parsed object.
Upvotes: 7
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