Page 1 of 1

Contact Form

Posted: Sun Nov 17, 2013 11:48 pm
by cheng412
this problem has cracked my head for a long time.
well, i want to create a ('form.html') and a ('form.php')
inside form.html it likes that >>>

Code: Select all

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<p><span class="error">* required field.</span></p>
<form method="post" action="form.php">
   Name: <input type="text" name="name" value="<?php echo $name;?>">
   <span class="error">* <?php echo $nameErr;?></span>
   <br><br>
   <input type="submit" name="submit" value="Submit">
</form>

</body>
</html>
and inside form.php >>>

Code: Select all

<?php
$name=$_POST["name"];

if (empty($name))
     {$nameErr = "Name is required";}
	if (!preg_match("/^[a-zA-Z ]*$/",$name))
		 {
       $nameErr = "Only letters and white space allowed";
       }
   else
     {echo $name;}	

function test_input($data)
{
     $data = trim($data);
     $data = stripslashes($data);
     $data = htmlspecialchars($data);
     return $data;
}
?>


and now my question comes... if i submit the form in empty form... it should be display "name is required" just beside the
text box in the form... unfortunately, it does not... it moves away to form.php... any help please? emergency!!! :banghead: :banghead: :banghead: :crazy: :crazy: :crazy:

Re: Contact Form

Posted: Mon Nov 18, 2013 2:10 am
by Eric!
The problem you are having here and here is with how forms and PHP work together.

Say you have an HTML page with a form called:
html_page_with_form.html

In that form you tell the browser to send the data to a page called:
html_form_processor.php

Once a user clicks SUBMIT, the browser is going to send the data to the page your form indicates ("html_form_processor.php"). Then it is done. There is no automatic reloading of the original page ("html_page_with_form.html"). The browser posts the data to the page and waits for a response from the server to send back an answer (in HTML).

So your page processing the form must give the browser an answer. This means your html_form_processor.php needs to redisplay the form with the error message. You can do this by adding an:

Code: Select all

include("html_page_with_form.html");
in the html_form_processor.php page after you are done checking all the submitted data and generated your error strings. Or you can do something more interactive. But first you need to understand that once the browser sends the form data, the server has to send back some HTML as an answer.

I suggest you look into some basic PHP form tutorials to get a better idea of how this mechanism works.