i got a little problem with my ajax response
this is my javascript code

$("#txt-cmt").keypress(function(e) {

    if(e.which == 13) {
        var comment = $(this).val();
        var message = {
            action: "show_comment",
            user_message: comment,
            dataType: 'json'
        };

        $.post(ajaxUrl.url, message, function(data){
            console.log(data);
        });
    }
});

when i console.log(data) it’s show my real data like this

{"content":"apple"}

now my problem is when i access json data like this

console.log(data.content);

it’s show undefined
and i try to use JSON.parse(data); but i got error like this

 Uncaught SyntaxError: Unexpected token  in JSON at position 0 /wordpress/#:1
    at JSON.parse (<anonymous>)
    at Object.success (comment-mu.js?ver=4.7.5:26)
    at i (jquery.js?ver=1.12.4:2)
    at Object.fireWith [as resolveWith] (jquery.js?ver=1.12.4:2)
    at y (jquery.js?ver=1.12.4:4)
    at XMLHttpRequest.c (jquery.js?ver=1.12.4:4)

and here is my php code with ajax action hook

add_action("wp_ajax_show_comment", "mu_show_comment");

function mu_show_comment() {

    $message = isset($_POST['x']) ? $_POST['x'] : 'no message found';

    $info = [
        "content" => "apple"
    ];

    echo json_encode($info);
    exit;
}

Read more here: ajax response Json Data Undefined wordpress, please anybody help me :'(


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: