简体   繁体   中英

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?

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'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM