Create a simple AJAX contact form with jQuery and PHP


Create a simple AJAX contact form with jQuery and PHP

Surfing the web today is simply amazing: websites of big companies looks gorgeous (well...not everyone, but the most), simple web applications tries to give stunning user experience with motion effects and nice web page transitions.

To give the user a feeling of continuity between change pages, launch actions and interactions between different aspect of the website, developers use AJAX techniques (Asynchronous JavaScript and XML), the way to manipulate data and interact with a server asynchronously, in background, like a ninja.

Forms are also touched by this trend: validation and submission are done in silent way, without reloading the page and using nice animation effects.

In this post I want to show you how to create a simple AJAX form using PHP and JavaScript, with the help of jQuery. Of course, JS will do the do the client-side actions (submission and 'thank you' message), PHP instead will do the server-side work (composing and sending e-mail).

Let's start!


The boring part: HTML

It's a dirty job, but somebody's gotta do it.

Work with HTML, specially with form structures, sometimes could be really, really, reeeeeeeally boring, but this is the base of everything is on the web. Let's create a simple HTML form:

<form name="my-form" method="POST">  
    <input type="text" id="name" name="name" value="" placeholder="Name" />
    <input type="email" id="email" name="email" value="" placeholder="E-mail" />
    <textarea id="message" name="message"></textarea>
    <input type="submit" id="submit" value="SUBMIT" name="submit" />
</form>  

The server-side part: PHP

With PHP we can do the real task: sending our e-mail. Create a file called send-mail.php and write a simple code to check the values, compose the message and send the e-mail.

<?php

    $to = "my-email@mydomain.com";

    if($_POST){
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];
        mail($to, "New message from " . $name, $message, "From: $email" );
    }
?>


What this script does is simple: save the message destination, check the form values sent via HTTP POST, send the email using a mail() method.


The client-side part: JavaScript

Finally, our AJAX call. We will use our friend jQuery with its amazing $.ajax() instruction, a simple way to call external resources and get a "feedback" from them.

// click action on submit button
$('#submit').on('click', function(){

    // get form values and compose a data string
    var name = $("#name").val();
    var email = $("#email").val();
    var message = $("#message").val();
    var data ='name=' + name + '&email=' + email + '&message=' + message;

    // AJAX call passing dataString in POST
    $.ajax({
        type: 'POST',
        data: data,
        url: 'send-mail.php',
        success: function(){
            // success callback
            console.log('message sent! :D');
        }
    });

    // prevent the default submit action
    return false;
});


What happened here is simple: when someone click on the submit button, we collect the data value from our form and create a string, then pass it via AJAX to our PHP script using HTTP POST. When the script have done its job, success callback will be triggered.


The fully road

So, let me explain for the last time the road of our AJAX form:

  1. The user fill our form an press submit
  2. JavaScript trigger an onClick action and launch our AJAX call to send-mail.php
  3. PHP get the form value via HTTP POST and send the email
  4. JavaScript again, launch the success callback

What can we do now?

Yeah, we have a simple AJAX form here...but is it maybe toooooooo much simple?

We can add to our form a lot of new features to give him more usability, stunning animations and much more.

  • Validation system: validation is always a good thing for a form. We can decide what field are required and give them a required attribute: HTML5 will do the job. (We can also use some JS library to do the job)
  • Loader: when we work with AJAX, we load external resources in silent way. The user maybe don't know what it's happening. Display a simple loader spinner when the user have clicked our submit button could be a great idea to give him a feedback of his action: "Hey, you have submitted the form! We are working for you...please wait a moment! ;)".
  • Success message: in the example showed above, on the success callback I simply do a console.log(). In this place could be a veeeeeery good option show a "Thank you!" message to give to the user the final feedback.

Those are only 3 extra-features: you can do others, immagine new one to create stunning and full customized forms.
Hope this post will help you, for integrations and questions, post a comment below. Cheers!



Daniele Petrarolo

Daniele Petrarolo

http://www.danielepetrarolo.com

In love with #JavaScript, #PHP and #Python / Web Developer / There's no place like 127.0.0.1.

View Comments