How to pass form input value to php function

forms, function, html, php

Solution

Make your `action` empty. You don't need to set the `onclick` attribute, that's only javascript. When you click your submit button, it will reload your page with input from the form. So write your PHP code at the top of the form.

<?php
if( isset($_GET['submit']) )
{
    //be sure to validate and clean your variables
    $val1 = htmlentities($_GET['val1']);
    $val2 = htmlentities($_GET['val2']);

    //then you can use them in a PHP function. 
    $result = myFunction($val1, $val2);
}
?>

<?php if( isset($result) ) echo $result; //print the result above the form ?>

<form action="" method="get">
    Inserisci number1: 
    <input type="text" name="val1" id="val1"></input>

    <?php echo "ciaoooo"; ?>

    <br></br>
    Inserisci number2:
    <input type="text" name="val2" id="val2"></input>

    <br></br>

    <input type="submit" name="submit" value="send"></input>
</form>

Problem

I want to write a php page in which there is a html form. I want to send all input (number for example) of my form to a php function (instead of a javascript function; I make this to hide my javascript function code). How can I send input value to php function? Is it possible to call the php function through `onclick="function(param1, param2)"`? I know that javascript is a client-side language while php is server-side. If it is possible, how can I write the return of the function in an input field? I want to remain in my page. Is it correct - `action="#"`? My code is: ``` <form action="#" method="get"> Inserisci number1: <input type="text" name="val1" id="val1"></input> <?php echo "ciaoooo"; ?> <br></br> Inserisci number2: <input type="text" name="val2" id="val2"></input> <br></br> <input type="submit" value="send"></input> </form> ``` Help me in the implementation of the simple php function and in the passage of values from input to function! Thanks!

Original source