Welcome to part 2/2 of the “Create a HTML5 form and submit it using AJAX” tutorial series. In this, the second part of the tutorial, we will be looking at submitting the form using jQuery & AJAX. If you happened to miss the first tutorial, please use the link below to access it.
Part 1 – Creating the HTML5 form
End Result:
Send us a message
Foreword:
Before we jump into the tutorial, I though it may be useful to give a brief introduction to AJAX and why you should consider using it. If you are already familar with the technology, then you may prefer skipping straight to “Step 1″.
What is AJAX?
AJAX is an acronym for Asynchronous JavaScript and XML. For some of you, that may give you a good idea of what the technology is all about. If you are still scratching your head though, don’t worry just yet, i’m sure the following explanation will clear things up.
A good place to start is probably with the word ‘asynchronous’. An asynchronous request/event is one which does not interrupt the main flow of the application; the request/event is independent of the main application. You can see an example of this on livescore.com. Every so often the page content is refreshed and any scores which have changed since the last request are updated. This is most likely implemented using javascript in combination with a backend language such as PHP, using the AJAX method.
So, In a nutshell, AJAX is a method of sending HTTP requests to the server without having to reload the current page, or having to access a new page.
How AJAX works
The list below gives a cursory overview of the process:
- An client-side event occurs ( button click for example).
- A XMLHttpREQUEST object is created & configured – callback function is defined at this point.
- The request object sends and asynchronous request to the server.
- After processing the request the server returns the data ( normally XML or json).
- The request object calls the callback function.
- At this stage the callback function runs – normally making changes to the DOM (or webpage to be slightly less technical).
Although this process is actually quite simple, there is a slight level of complexity involved in ensuring the request object functions across a wide range of browsers. Thankfully jQuery abstracts a lot of the complexity away and reduces the coding time significantly.
With AJAX now introduced, let’s move on with the tutorial.
STEP 1 – Create PHP script which will handle the HTTP request.
The actual server-side processing is outside the scope of this tutorial, so instead, I have created a dummy script which we will use for demonstration purposes. The script will not focus on sanitizing, validating or processing the data and will instead simply return a message based on the user input. If all fields have been supplied, then a success message is returned, else an error message is returned.
The code can be seen below.
<?php //Setting the Content type. Basically telling the browser what type of content it //is dealing with. header('Content-type: application/json'); //Extracting the variables from the POST superglobal. $name = $_POST['yourName']; $email = $_POST['yourEmail']; $comments = $_POST['yourComments']; //Creating arrays which will hold our data. $errors = array(); $message = array() //Have all required fields been filled out? if ( isset($name) && isset($email) && isset($comments)) { //You would normally do some processing here before entering the data //into the database. //As we are just demoing AJAX, lets pause for a litle while and then return the //message in json format. sleep(1); $message[] = "Thanks, your message was processed successfully, please stay tuned for a reply"; //Output the data in JSON format. echo json_encode($message); } //Required vars not set, lets send error message back. else { //Again sleep for a second. sleep(1); //Check each of the values, adding an error to the array if it is not set. if (!isset($name) ) { $errors[] = "The name field is a required field."; } if (!isset($email) ) { $errors[] = "The e-mail field is a required field."; } if (!isset($comments) ) { $errors[] = "The comments field is a required field."; } //Again output data in json format. echo json_encode($errors); } ?>
As the script is very basic I wont go over the code in any detail – the comments should hopefully be enough. We are now ready to handle the form submission using AJAX.
STEP 2 – Submitting the form using jQuery AJAX.
As we are using jQuery, the first thing we need to do is include the library in our webpage. You can either download the library, or use a hosted version (recommended).
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
OK – let’s get on with the form submission.
Before any of our code executes, we want to ensure the DOM is fully loaded. It is possible to achieve this through use of the ‘ready()’ method which accepts a handler as its parameter; the handler being a function which is called when the DOM is fully loaded. Take a look at the code below to see how this works.
//Passing an anonymous function as the event handler. $(document).ready(function() { //Our code will be added here & will not execute until the DOM is fully loaded. });
If you read through the list at the top of this tutorial(outlining how AJAX works), you may have already guessed what the next step is. We need to add an event listener that will initialize the AJAX request… since we are handling a form submission, lets use the ‘submit()’ event listener.
//Passing an anonymous function as the event handler. $(document).ready(function() { //Adding submit listener to our form, again with anonymous function as handler. $('#sampleForm').submit(function(e) { //Prevent the default action, which in this case is the form submission. e.preventDefault(); //Serialize the form data and store to a variable. formData = $(this).serialize(); }); });
If you try to submit the form now, you will notice that nothing happens. This is due to the ‘preventDefault’ method disabling the default event behaviour. We are now ready to create the AJAX request, using the jQuery ‘ajax’ method.
//Passing an anonymous function as the event handler. $(document).ready(function() { //Adding submit listener to our form, again with anonymous function as handler. $('#sampleForm').submit(function(e) { //Prevent the default action, which in this case is the form submission. e.preventDefault(); //Serialize the form data and store to a variable. formData = $(this).serialize(); //Perform an asynchronous HTTP (Ajax) request. $.ajax({ //This URL to which the request is sent url: "process_sample_form.php", //The data which will be passed along with the request. data: formData, //The type of request to make ( GET or POST) type: "POST", //The type of data which is returned. dataType: "json" //The callback function which is called if the request has been successful. }).done(function ( data ) { //You would generally make changes to the DOM at this stage, maybe //adding a success message to the form. alert(data); //The callback function which is called is the request fails. }).fail(function() { //You would generally make changes to the DOM at this stage, maybe //adding a failure message to the form. alert("Sorry, there seems to be a problem contacting the server."); }); }); });
If you look closely at the code above, you will notice that we have passed one parameter to the ‘ajax’ method. To be more specific we have passed an object which contains a number of key/value pairs used to configure the request. I’ve stripped the object out from the code and included it below so you can see this clearly.
{ //This URL to which the request is sent url: "process_sample_form.php", //The data which will be passed along with the request. data: formData, //The type of request to make ( GET or POST) type: "POST", //The type of data which is returned. dataType: "json" //The callback function which is called if the request has been successful. }
Notice that the script is sending a ‘POST’ request to the server. By doing so, the form data will be stored in the ‘POST’ super global, which is where our PHP script is looking for the values. Had we used a ‘GET’ request instead, then the data would be stored in the ‘GET’ super global.
It’s probably worth noting at this point that using this method it is not possible to make cross domain requests – you will need to make sure that the ‘url’ option is pointing to a local script; a script hosted on the same server from which you are making the request. If you are interested in making cross domain requests, this cross domain ajax tutorial may be of some use.
There are many more options available to the ‘ajax’ method, the jQuery documentation outlines and explains these options better than I ever could. So if you are interested, go take a peak!
Thanks for reading, any comments or questions just leave’em below and i’ll be in touch. Cheers.
The post Create a HTML5 form and submit it using AJAX. Part 2/2. appeared first on Weebtutorials.