AJAX PHP Form

PHP comes packed with a powerful mail function that makes sending emails super easy. Using some basic PHP and Javascript we can create a simple contact form that is submitted via AJAX.  Using AJAX to submit the form isn’t necessary, but I really love the seamless user experience that AJAX helps to provide and it makes this code that much more portable in case you want to put it inside a modal popup or sidebar widget.

Lets start with the form

Pretty simple stuff here, just note that the action for this form is set to mail.php and the ID is set to contactform, this will be important later. There are two divs below the form that we will display on success or error after the form is submitted. You can write some CSS to hide the class hidden to keep them hidden for now. There is a simple captcha included with the form that is generated with PHP and we will use it to stop basic bots from spamming our form. Consider using Google’s reCAPTCHA for better spam protection. The captcha.php file looks like

Inside the mail.php file we will check the captcha, sanitize the submitted user inputs, and then send the mail. If the mail is sent we will set the status variable inside a JSON array to be success. If the captcha doesn’t match we will set the status to error inside the JSON array. The status codes will help us correctly show the error or success divs on the front end.

The final piece to the puzzle will be some jQuery. In the jQuery we will use AJAX to submit the form and we will also take some actions based on the status code that is returned to us from the mail.php file. We will display the alert-success div if the status code is success and we will display the alert-error div if the status code is error. On success we will also want to clear the form fields and refresh the captcha image.

Leave a Reply