I have home.php and I am trying to pass two php variables in an onclick() function. But it does not work. I am new in php so any suggestion will be very helpful.
<form action="process/home.php" method="post">
<input type="text" name="userfrom" value="<?php echo htmlspecialchars($username); ?>"/>
<input type="submit" onclick=show('$user_id','$_SESSION['id']') value="Add Friend"/>
</form>
In the show() function I wanted to store the values in the database.
function show($userfrom,$userto){
$sql="INSERT INTO user (userfrom,userto) VALUES ('$userfrom','$userto')";
mysql_query($sql);
<!--it is not working-->
}
3 Answers 3
Your are new in php. So, remember this, you can't use PHP functions in JS code. onClick event needs js function. So firstly, you should pass your variables, with form then get it and after that you can use php functions.
You can use this code, but not recommended
<form action="" method="post">
<input type="text" name="userfrom" value="<?= htmlspecialchars($username); ?>"/>
<input type="submit" name="addFriend" />
</form>
<?php
if (isset($_POST['addFriend'])) {
show($user_id, $_SESSION['id']);
}
?>
You should learn about jquery ajax. (Advice for you)
Comments
Try below code, You have some syntax errors,
<form action="process/home.php" method="post">
<input type="text" name="userfrom" value="<?php echo htmlspecialchars($username); ?>"/>
<input type="submit" onclick="show(<?php echo $userid ; ?>, <?php echo
$_SESSION['id']; ?>)" value="Add Friend"/>
</form>
1 Comment
You need to echo your php variables into HTML elements.
onclick=show('<?=$user_id;?>','<?=$_SESSION['id'];?>')
shorthand for echo: <?=
and don't forget to add quotations when passing string values.