Tal Tal - 22 days ago 5
HTML Question

is it possible to execute some php code after html form post?

i'm new to php, html and web services.
what i'm trying to do is to send a First name variable with HTML form to a webservice and to echo it's respond back to the same page of my form. now my problem is that the call for the web service happens before i post the firstname variable. is there a way to execute the rest of my php code after i click the submit button? so i will be able to call the web service after the firstname variable is set.

this is my code i tried some stuff but they didn't really helped me.
thanks.

<?php
$path = 'c:\\wamp\\www\\nusoap.php';
require_once $path;
$client = new nusoap_client("http://localhost/nusoap/productlist.php?wsdl", TRUE);

?>
<html>
<head>
<title>Personal INFO</title>
</head>
<body>
<?php
echo '<form method="post" action="">';
echo 'First Name:'; echo '<input type="text" size="12" maxlength="12" name="Fname">'; echo '<br />';
'<input type="submit" value="Submit" class="button">
</form>'
?>
<?php
if (isset($_POST['Fname']))
{
$Fname = $_POST["Fname"];
$result = $client->call("getName", array($Fname));
}
//echo $Fname;

$error = $client->getError();
if ($error) {
echo "<h2>Constructor error</h2><pre>" . $error . "</pre>";
}
if ($Fname != NULL or ""){
//$result = $client->call("getName", array($Fname));
}
if ($client->fault) {
echo "<h2>Fault</h2><pre>";
echo ($result);
echo "</pre>";
}
else {
$error = $client->getError();
if ($error) {
echo "<h2>Error</h2><pre>" . $error . "</pre>";
}
else if (isset($Fname)){
echo "<h2>Respond</h2><pre>";
echo $result;
echo "</pre>";
}
}
?>
</body>
</html>

Answer

To check if the form has been submitted or not you can use the following code:

<form action="#" method="POST">
    <button type="submit">Submit</button>
</form>
<?php
     if( $_SERVER['REQUEST_METHOD'] == "POST" ){
          // Do something with posted data
          // For example: if( isset( $_POST['Fname'] ) ) { echo $_POST['Fname']; }
     }
?>

$_SERVER is a global array containing multiple array keys with information about how the server was called, the visitor and such. Here we use it to check the request method, which in this case is POST when an form has been submitted.

The isset() function checks to see if the assigned string or array actually exists. So in this case we make a IF statement with it, saying that if the variable $_POST['Fname'] in fact does exist, we should do something. you can also do the opposite by adding an ! in front of it. This will say that if the value is NOT set:

if ( !isset( $_POST['Fname'] ) ) { echo "Did you forget your name?"; }