【问题标题】:Passing js variable to php using ajax does not work使用ajax将js变量传递给php不起作用
【发布时间】:2022-02-08 02:27:52
【问题描述】:

我想在我的 php 文件中获取变量 rating_idex,所以如果用户单击按钮 #add-review 它应该传入 ajax 变量,它将在 php 文件中获取数组并将评论发送到数据库,但它不工作并且我没有看到解决方案

$('#add-review').click(function(){
    var user_name = $('#reviewer-name').val();
    var user_review = $('#review').val();
    console.log(user_name);
    console.log(rating_index);
    console.log(user_review);
    if(user_name == '' || user_review == '')
    {
        alert("Please Fill Both Field");
        return false;
    }
    else
    {
        $.ajax({
            url:"rating-data.php",
            method:"GET",
            data:{
                rating_index: rating_index,
                user_name: user_name,
                user_review: user_review
            },
            success:function(data)
            {
                $('#review_modal').modal('hide');
                load_rating_data();
                console.log(data);
            }
        })
    }
});

当我可以获取变量并将它们发送到数据库时,这是我的 php 代码:

<?php 
include 'connection.php';
echo ($rating_index);
if(isset($_GET["rating_index"]))
{
    $data = array(
        ':user_name'        =>  $_GET["user_name"],
        ':user_rating'      =>  $_GET["rating_index"],
        ':user_review'      =>  $_GET["user_review"],
        ':datetime'         =>  time()
    );
    $query = "
    INSERT INTO review_table 
    (user_name, user_rating, user_review, datetime) 
    VALUES (:user_name, :user_rating, :user_review, :datetime)
    ";

    $query_run = mysqli_query($conn, $query);
    if($query_run){
        echo "Your Review & Rating Successfully Submitted";
    } else{
        echo '<script type="text/javascript"> alert("Something went wrong") </script>';
        echo mysqli_error($conn);
    }
}
?>

当我尝试回显 ($rating_index) 时,它给我反馈说变量不存在,所以它是 ajax 的东西,但找不到解决方案,提前感谢任何解决方案

【问题讨论】:

  • 你为什么期望变量$rating_index存在?!
  • @deceze 它确实存在我有很多代码行,这就是为什么我不能在这里传递所有内容。所有变量在 JS 中都有值。你可以看到我使用 console.log 来检查它们的值。
  • JS 设置user_nameuser_review。它在哪里设置rating_index
  • 无论如何,你应该在 echo 之前做 $rating_index=$_GET["rating_index"]

标签: javascript php mysql ajax


【解决方案1】:

而不是echo ($rating_index); 尝试echo ($_GET["rating_index"]); 原因是你实际上没有声明$rating_index

【讨论】:

    【解决方案2】:

    如果我没记错的话,你想在 javascript 中传递 PHP 变量吗? 如果是,你不能像这样在 js 中传递 PHP 变量。

    var x = " < ? php echo"$name" ? >";
    

    你可以像这样传递你的 PHP 变量,但只能在 .php 文件中,而不是在 .js 中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 2011-09-02
      • 1970-01-01
      相关资源
      最近更新 更多