0

I want to send a javascript variable to php file which shows the comments on a webpage.

I was able to send this js variable to some other php file, but I can't do it with this comment-list.php file. I guess there is some problem with JSON.

function listComment() {

        $.ajax({
            url: "Komentarji/comment-list.php",
            data : {page_num: page_num},
            type : 'post',
            success : function(response) {
            }
        });

        $.post("Komentarji/comment-list.php", function(data) {
                            var data = JSON.parse(data);
.
.
.

The function is called here:

$(document).ready(function() {
        listComment();
    });

Inside comment-list.php I try to get the variable that was sent with ajax. However it doesn't work and comment's aren't displayed on page. If I delete this line, the comments work again (but of course, I don't get the sent variable).

$num = $_POST['page_num'];

$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";

$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
    array_push($record_set, $row);
}
mysqli_free_result($result);

mysqli_close($conn);
echo json_encode($record_set);

Here is the javascript variable and included php file.

<script>
var page_num = 1;
</script>
<?php
include($_SERVER["DOCUMENT_ROOT"]."/index.php");
?>

I get this error in console: Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse ()

As said eariler if I remove the line where I get the variable with post, this error disappears.

2
  • In the Ajax call you can define the way the response should be interpreted as. Adding dataType : "json" as a propery to the json object sent as a parameter to the Ajax call should resolve this issue. json_encode() in php will convert a php object(array) to a json string. So you either att the dataType : "json" row or you can parse the response using JSON.parse(response) in the success method. Hope this helps, got any questions? go ahead and ask Commented Jun 1, 2019 at 20:31
  • I added the dataype json, but it didn't solve the problem. Commented Jun 2, 2019 at 12:57

2 Answers 2

1

You shouldn't use $.ajax and $.post to do the same thing, pick one, I'd say remove the $.post one and dont forget to put an exit; statement after you echo the response to avoid PHP to process further code if existing, also worth mentionning but not necessary, you can put the dataType to json so dataType: 'json' in the $.ajax call, dataType is used to tell jQuery what to expect as a response type from the server, as you are echoing the response by encoding it in JSON, you won't need to parse the response on your JS side if you speficied the dataType beforehand.

 $.ajax({
        url: "Komentarji/comment-list.php",
        data : {page_num: page_num},
        type : 'post',
        dataType: 'json',
        success : function(response) {
            console.log(response); //will show the result of echo json_encode($record_set); from your PHP
        }
    });


$num = $_POST['page_num'];

$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";

$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
    array_push($record_set, $row);
}
mysqli_free_result($result);

mysqli_close($conn);
echo json_encode($record_set);
exit; //exit statement here

Following discussion with OP who wanted to use the $.post method, this is how it is done, pass the data as an object to the second attribute (more infos here):

$.post("Komentarji/comment-list.php", {page_num: page_num});
Sign up to request clarification or add additional context in comments.

4 Comments

How would I convert this post to ajax?
You mean $.post instead of $.ajax?
Yes, here is the code for $.post pastebin.com/gKc6QVJy, I should mention that I only need to send page_num variable to comment-list.php to check on which page I submitted the comment, I don't need to get the variable back.
Then just do it like so $.post("Komentarji/comment-list.php", {page_num: page_num})
0

Just make your format JSON in your JS script

$.ajax({
    url : 'Komentarji/comment-list.php',
    type: "POST",
    data: page_num:page_num,
    dataType: "JSON",
    success: function(data)
    {
        console.log(data);            
    },
    error: function (jqXHR, textStatus, errorThrown){
        console.log(errorThrown);
    }
});

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.