首页 > 解决方案 > 在 HTML 中的 onclick 函数参数中发送 php 变量在循环中不起作用

问题描述

让我知道我错在哪里。我一直在尝试在 onclick 函数参数中发送 php 变量,但它不起作用。参数在 InsertReply 函数中传递。这是代码:

$sql22 = "SELECT * FROM comments WHERE PostID=$id";
$count22=$conect->query($sql22);
if($count22->num_rows>0){               //If comments exist
while($row = $count22->fetch_array()){      //Fetching Comments
    $mail = $row['UserMail'];
    $comment = $row['Comment'];
    $comment_id = $row['ID'];
     echo "<br>";
     echo "<p>".$comment_id."</p>";
    // Reply input field starts 
    ?>
     <input type='text' name='reply' id='reply' placeholder='Enter Reply here' min='5' max='100' class='big-input' style='width:40%;margin-left:40px;margin-right:40px;'>
 <?php
                    echo "<input type='hidden' name='mail' id='mail' value= '".$current_user."'/>";
                    echo "<input type='hidden' name='postid' id='postid' value= '".$id."'/>";
echo "<button class='btn btn-outline-info' onclick='InsertReply(<?php echo $comment_id ?>)'>Reply</button>";
}       
}

这是 InsertReply 函数:

function InsertReply(x) {
alert("Insert Reply Function Called! with comment id : " + x);
//Storing values in variables
var reply = document.getElementById("reply").value; 
var mail = document.getElementById("mail").value;
var p_id = document.getElementById("postid").value;
alert("Reply is "+reply);

alert("Reply will be added with Reply : " + reply + ", by : "+ mail + ", Post ID : " + p_id + " & Comment ID : "+x);

我知道代码有很多问题。请指导我,因为我被严重卡住了。让我知道是否需要其他任何东西。我只想将变量值发送到 InsertReply 函数。任何替代方法或建议将不胜感激。

标签: javascriptphphtmlforms

解决方案


echo "<button class='btn btn-outline-info' onclick='InsertReply(<?php echo $comment_id ?>)'>Reply</button>";

您已经在呼应它,所以像这样传递值

echo "<button class='btn btn-outline-info' onclick='InsertReply($comment_id)'>Reply</button>";

推荐阅读