You are here
jquery contact form with ajax and php PHP PHP Coding 

How to Create a jQuery Contact Form with Ajax and PHP

jQuery Contact Form with Ajax and PHP.

We have created a simple HTML form with four fields Name, Email, Gender, Bacon and check me.


HTML : – Html to build the structure of your contact form
PHP : – Use PHP to process the data to make  and PHP mail() function to be used to send email.
Ajax & Jquery : – Through jQuery user can submit the forms and you can put validation using jquery.

HTML Form  (contact-form.html):

<form method='post' action='/contact.php'>
    Name: <input type='text' name='name' required><br>
    Email: <input type='email' name='email' required><br>
    Gender: <select name='gender'>
        <option value='m'>Male</option>
        <option value='b'>Bacon</option>
        <option value='f'>Female</option>
    Bacon: <input type='radio' name='bacon' value='smoked' checked> <input type='radio' name='bacon' value='unsmoked'><br>
    Check Me: <input type='checkbox' name='checkme'><br>
    <input type='submit' value='Send'>

PHP Script  (contact.php):


// Blank message to start with so we can append to it.
$message = '';

// Check that name & email aren't empty.
if(empty($_POST['name']) || empty($_POST['email'])){
    die('Please ensure name and email are provided.');

// Check the checkbox
$checkString = 'I have not been checked.';
    $checkString = 'I have been checked.';

// Construct the message
$message .= <<<TEXT
    Name: {$_POST['name']}
    Email: {$_POST['name']}
    Gender: {$_POST['gender']}
    Bacon: {$_POST['bacon']}    

// Email to send to
$to = '';

// Email Subject
$subject = 'You have been contacted!';

// Name to show email from
$from = 'Your Site';

// Domain to show the email from
$fromEmail = '';

// Construct a header to send who the email is from
$header = 'From: ' . $from . '<' . $fromEmail . '>';

// Try sending the email
if(!mail($to, $subject, $message, $header)){
    die('Error sending email.');
    die('Email sent!');


Jquery Code :


        // Stop the form actually posting

        // Send the request
        $.post('/contact.php', {
            name: $('#name').val(),
            email: $('#email').val(),
            gender: $('#gender').val(),
            bacon: $('.bacon:checked').val(),
            checkme: $('#checkme').is(':checked')
        }, function(d){
            // Here we handle the response from the script
            // We are just going to alert the result for now





Related posts

Leave a Comment