anonymous
anonymous

Reputation: 1

php global variables in ajax

So i have a page called user.php as test

<?php 
$user = $_GET['userID'];
echo $user;
?>

then i have .js that uses ajax to add a comment on the profile which works but the php that it uses (select and insert) is in a file called profileComments.php

$.ajax({
        url: 'profileComments.php',
        method: 'POST',
        async: false,
        data: {
            display: 1,
            user: userID
        },
        success: function () {
            insertComments();
        }
    });

now i want to edit the select query of that profileComments.php file to only display those with the right userID

<?php
include "db.php";
$user = $_GET['userID'];

if (isset($_POST["display"])) {
  $comments= "SELECT * FROM comments";
  $query= mysqli_query($connection, $comments);

  while ($comments = mysqli_fetch_assoc($query)) { ?>
        <li>
            <?php echo $comments["content"]?>
        </li>
    <?php }
}

But the problem is when I edit it in

"SELECT * FROM comments WHERE userID = $user"

at the top i've written this $user = $_GET['userID']; but it gives me the unidentified error

How can i make this work?

Upvotes: 0

Views: 273

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35337

You're using AJAX to send a POST request, not a GET request (See the method value of your ajax request). Therefore, all of the data in that AJAX request will be read into the $_POST superglobal of PHP.

You also named that key 'user', not 'userID' (see the data value of your ajax request).

Try:

$user = $_POST['user'];

Upvotes: 1

Related Questions