0

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

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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

It will not call php function, this is only called javascript function you need to use Ajax to call php function.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.