I have met with this error telling me that there is an unexpected token C pointing to my Jquery file. After much research, i am under assuming that the reason why i am getting this error is because the Json value passed back is already decoded and thus decoding it again will result in this error.
Is this statement true ? or is there another reason behind ? This is my what my json data looks like [{"comments":"Greta"},{"comments":"John"}]
<a onclick="showUser('.$row['ID'].')" >Show Comments</a>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
$.ajax({
type:'post',
url: 'viewCommentsJson.php',
data:{q:str},
success:function(data)
{
data = $.parseJSON(data);
var response;
$.each(data, function(index, value){
response += value+'<br />';
});
$('#txtHint').html(response);
}
});
}
</script>
The reason is that, you are trying to parse the response which is already in json format.
$.parseJSON method should apply in string type. Since your server response is json, you dont have to parse it again.
Change your code like this,
$.ajax({
type: 'post',
url: 'viewCommentsJson.php',
data: {
q: str
},
success: function (data) {
var response = "";
$.each(data, function (index, value) {
response += value.comments + '<br />';
});
$('#txtHint').html(response);
}
});
This is presumable because the response is 'Connection failed ...' and you are trying to parse the database output to JSON, when the connection was refused.
This would cause the C to be parsed and would throw an "Unexpected token C" error.
Check your 'network' tab in your inspector and look for the .PHP SQL script. At least in the chrome inspector you can get the response and see when kind of response you are getting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With