0

I can't figure it out why I am getting error "JSON.parse: unexpected character" in Firefox console.. Looks like the problem is around jQuery.parseJSON(data)); in comment.js file.. If I remove both if statements in my php file works everything well, but this is not what I need..

Thanks!

comment.php

<?php

require_once ("../modules/comments.php");
require_once ("../includes/db_connect.php");

 if(isset($_POST['task']) && $_POST['task'] == 'comment_insert' ) {

    $userId = (int)$_POST['userId'];
    //$comment = addslashes(str_replace("\n", "<br>", $_POST['comment']));

    $comment = strip_tags($_POST['comment']); // remove html tags
    $comment = ucfirst(strtolower($comment)); 
    //$comment = addslashes(str_replace("\n", "<br>"));

    $std = new stdClass();
    $std->commentId = 24;
    $std->userId = $userId;
    $std->comment = $comment;
    $std->userName = "John Stu";
    $std->profile_img = "https://s.ytimg.com/yts/img/avatar_48-vfllY0UTT.png";

     if(class_exists('Comments') && class_exists('Subscribers')) {

        $commentInfo = Comments::insertComments($comment, $userId);

        if($commentInfo != null) {


        }

    }   
        echo json_encode($std); 



 } else {

   //header("Location: /");

 }

?>

comment.js

$(document).ready(function(){

    $('#post-comment-btn').click(function(){
        comment_post_btn_click();

    });

});


function comment_post_btn_click(){

var _comment = $('#comment-post-text').val();
        var _userId = $('#userId').val();
        var _userName = $('#userName').val();

        if(_comment.length > 0 && _userId != null) {

        $.post("ajax/comment_insert.php", {
            task    : "comment_insert",
            userId  : _userId,
            comment : _comment,

        }).done(function(data) {

         comment_insert(jQuery.parseJSON(data));    
         console.log("ResponseText:" + data);

            });

            console.log(_comment + " Username: " + _userName + " User Id: " + _userId);

        } else {

            console.log("The text area is empty..");

        }

        $('#comment-post-text').val("");

}

function comment_insert(data) {


    var t = '';

    t += '<li class="comment-holder" id="_'+data.comment_id+'">';                       
    t += '<div class="user-img">';
    t += '<img src="'+data.profile_img+'">';
    t += '</div>';
    t += '<div class="comment-body">';
    t += '<h3 class="username-field">'+data.userName+'</h3>';
    t += '<div class="comment-text">'+data.commen+'</div>';
    t += '</div>';
    t += '<div class="comment-buttons-holder">';
    t += '<ul>';
    t += '<li class="delete-btn">X</li>';
    t += '</ul>';
    t += '</div>';
    t += '</li>';

    $('.comments-holder-ul').prepend(t);
}
5
  • can you show the output of console.log("ResponseText:" + data); ? Commented Sep 25, 2017 at 4:46
  • @tan I am getting only: "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data" Commented Sep 25, 2017 at 4:49
  • google chrome > VM7285:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0 at Function.parse [as parseJSON] (<anonymous>) at Object.<anonymous> (comment.js:26) at i (jquery.min.js:2) at Object.fireWith [as resolveWith] (jquery.min.js:2) at A (jquery.min.js:4) at XMLHttpRequest.<anonymous> (jquery.min.js:4) Commented Sep 25, 2017 at 4:50
  • It means you have error in your php code.. use try..catch and return exception as json response.. then you'll be able to see what is php error. Commented Sep 25, 2017 at 4:59
  • if you place the line console.log("ResponseText:" + data); before comment_insert(jQuery.parseJSON(data));, then it might output what data is in "data". Commented Sep 25, 2017 at 5:06

3 Answers 3

2

Looks like you have some Error/Warning in your PHP file. Try this, Inspect > Network >Select XHR and make the AJAX call. Now you'll see the PHP response in Response tab. (Better use Google Chrome)

Because PHP Errors/Warnings are wrapped up with HTML tags which starts from "<". (Example <div>Undefined Index</div>)

Sign up to request clarification or add additional context in comments.

Comments

0

First clean the output buffer and then terminate the current script. try below code:

comment.php

require_once ("../modules/comments.php");
require_once ("../includes/db_connect.php");

 if(isset($_POST['task']) && $_POST['task'] == 'comment_insert' ) {

    $userId = (int)$_POST['userId'];
    //$comment = addslashes(str_replace("\n", "<br>", $_POST['comment']));

    $comment = strip_tags($_POST['comment']); // remove html tags
    $comment = ucfirst(strtolower($comment)); 
    //$comment = addslashes(str_replace("\n", "<br>"));

    $std = new stdClass();
    $std->commentId = 24;
    $std->userId = $userId;
    $std->comment = $comment;
    $std->userName = "John Stu";
    $std->profile_img = "https://s.ytimg.com/yts/img/avatar_48-vfllY0UTT.png";

     if(class_exists('Comments') && class_exists('Subscribers')) {

        $commentInfo = Comments::insertComments($comment, $userId);

        if($commentInfo != null) {


        }

    }   

    // Clean the output buffer
    ob_clean();

    echo json_encode($std); 

    // Terminate the current script
    die();

 } else {

   //header("Location: /");

 }

?>

Comments

0

If you are returning json data, you have to indicate it to the $.post function in adding the last parameter (otherwise, data won't be a json object)...

$.post("ajax/comment_insert.php", {
    task : "comment_insert",
    userId  : _userId,
    comment : _comment,
},,"json").done(...

Change that and check if the error persists...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.