• hey guys i got a little problem with ajax response with json data

    here 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 access data like this console.log(data); it’s show real data like {"content":"apple"}
    but when i access data like this console.log(data.content) it’s show undefined
    how can i resolve this problem
    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;
    }
Viewing 2 replies - 1 through 2 (of 2 total)
  • Will you please give a try to php code like this

    add_action("wp_ajax_show_comment", "mu_show_comment");
    function mu_show_comment() {
    	$message = isset($_POST['x']) ? $_POST['x'] : 'no message found';
    	 $info = array(
    		 "content" => "apple"
    	         );
    	echo json_encode($info);
    	exit;
    }

    i think you were wrong here:

    
    $info = array(
    	 "content" => "apple"
             );
    

    Please give a try

    Thanks

    Moderator bcworkz

    (@bcworkz)

    iqbal1486 — thanks for your assistance, it is appreciated! However, the array declaration is not the problem. The square bracket array shortcut has been supported in PHP since 5.4. This is equivalent and fine to do: $info = ['content' => 'apple']; Until recently it was news to me as well ?? I think it has only recently caught on with many coders.

    motailab — console.log(data) is showing you the JSON string, it is not an actual array even though it looks like one, so console.log(data.content) is indeed undefined. For it to become a usable array you must parse the JSON with something like nuData = JSON.parse(data);.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘ajax response with json not working’ is closed to new replies.