'Passing a PHP variable to a php file using AJAX

I'm using this code for my comments section. here everything works, except when i try to send the "$post['id']" variable via AJAX to "fetch-comment.php" file i get this error:

    Warning: Undefined array key "load" in C:\xampp\htdocs\x\fetch-comment.php on line 5
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' parent='0' ORDER BY id DESC' at line 1 in C:\xampp\htdocs\x\fetch-comment.php:10 Stack trace: #0 C:\xampp\htdocs\x\fetch-comment.php(10): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\x\fetch-comment.php on line 10

here's my JS code:

$(document).ready(function() {

        $('#comment_form').on('submit', function(event) {
            event.preventDefault();
            var form_data = $(this).serialize();
            $.ajax({
                url: "../add-comment.php",
                method: "POST",
                data: form_data,
                dataType: "JSON",
                success: function(data) {
                    if (data.error != '') {
                        $('#comment_form')[0].reset();
                        $('#comment_message').html(data.error);
                    }
                }
            })
        });

        load_comment();

        function load_comment() {
            var load = <?php echo $post['id']; ?>;
            $.ajax({
                url: "../fetch-comment.php",
                method: "POST",
                data: load,
                success: function(data) {
                    $('#display_comment').html(data);
                }
            })
        }

        $(document).on('click', '.reply', function() {
            var comment_id = $(this).attr("id");
            $('#comment_id').val(comment_id);
            $('#comment_name').focus();
            $('#comment_content').attr('placeholder', 'Write Your Reply !');
        });

    });

and here's the part of php file that's throwing the error:

<?php

include "config/db.php";

$load = $_POST['load'];
$parent = 0; //when parent is zero it means it's original comment and not a reply
$comments = $conn->prepare('SELECT * FROM comments WHERE post=?, parent=? ORDER BY id DESC');
$comments->bindValue(1, $load);
$comments->bindValue(2, $parent);
$comments->execute();
$comments = $comments->fetchAll(PDO::FETCH_ASSOC);

i've been messing with the code for 10 hours straight, please help !



Solution 1:[1]

Shouldn't it be

data : {list : load}

in the ajax call and

$load = $_POST['list'];

in the php script. I see no listin $_POST array sent by the ajax call.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1