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>
    </select><br>
    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'>
</form>

PHP Script  (contact.php):

<?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.';
if(isset($_POST['checkme'])){
    $checkString = 'I have been checked.';
}

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

// Email to send to
$to = 'test@testdomain.com';

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

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

// Domain to show the email from
$fromEmail = 'YourSite@domain.com';

// 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.');
}else{
    die('Email sent!');
}
?>

 

Jquery Code :

$(function(){
    $('#form').submit(function(e){

        // Stop the form actually posting
        e.preventDefault();

        // 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
            alert(d);
        });
    });
});

 

 

 

 

Related posts

Leave a Comment