Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught SyntaxError: Unexpected token C - JQUERY - Passing and Decoding Json

Tags:

json

jquery

ajax

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>
like image 346
user2691544 Avatar asked May 08 '26 13:05

user2691544


2 Answers

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);
    }
});
like image 192
Anoop Joshi P Avatar answered May 10 '26 02:05

Anoop Joshi P


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.

like image 26
Ashes Avatar answered May 10 '26 03:05

Ashes