Basically, what I am going to show you today, is how to build HTML form which will then post data to a PHP script, which will do something interesting to that information.

I will be careful and use all securing techniques to teach you to use those techniques always, as securing the application is the most important task for every developer. You can read about those techniques in my PHP Security article.

So, let us build a simple form and collect name and email address from user:

[code lang=”html”]






[/code]

This is really simple form with two input fields and a submit button. When we press submit button, form will “post” values of name and email and send it to test.php which is our action parameter in above code. Save this code to form.php file.

Now let us create test.php file which will process the data:

[code lang=”php”]
Your name is ‘ . $name . ‘ and email: ‘ . $email . ‘

‘;
}
?>
[/code]

If you plan to enter the data posted into a database, you can use mysql_real_escape_string function. Save the above code to test.php and let us try it. Go to your form.php file, enter some data and press Send button. You should see that you are now on test.php page and a sentence with your name and email is written on top.

Basically, that is all you ever need. Now you can build a form for entering data into the database, or updating it, but that will be the topic of some future tutorial.

Let me extend this and show you how you can pass data to test.php using AJAX. This way your page will not refresh, nor take you anywhere. The sentence will be written instead of our form that we created earlier.

Open your form.php and directly below ending form tag add this line:

[code lang=”html”]

[/code]

This will be our placeholder for writing the resulting sentence. To do the AJAX magic, I will use jQuery, so be sure to call it by entering this code in your form.php file:

[code lang=”html”]

[/code]

Directly below everything in form.php file, enter this code:
[code lang=”javascript”]

[/code]

Now try it. Open your form.php in browser, type some values and submit it, and you should see form disappearing and sentence appearing. You do not have to change the test.php file, it is working as expected, securing user input and sending it back to form.php page.

This approach is great, as it will always work. If a user has turned off JavaScript, form will normally be posted and everything would work fine.