In this tutorial we will be submitting a form using AJAX with jQuery to PHP. What you need to understand is the jQuery is shorthand for JavaScript. jQuery has a bunch of JavaScript functions that make it shorter to call in when coding. This particular tutorial is related to our other post in JavaScript Best Ajax Tutorial Simple and Easy to understand. In that lesson we coded pure JavaScript. In this lesson we are going to do it with jQuery. If you want a better understanding of the differences between jQuery and JavaScript please see "AJAX Raw Or With jQuery Whats The Difference?"
jQuery Ajax Form Submit With PHP Processing
jQuery has main functions programmed into it. We will be making use of the following functions in jQuery.- The .ready() method offers a way to run JavaScript code as soon as the page's Document Object Model (DOM) becomes safe to manipulate.
- The click() event occurs when an element is clicked. The click() method triggers the click event, or attaches a function to run when a click event occurs.
- The .val() method is primarily used to get the values of form elements such as input , select and textarea .
Scripts for jQuery Tutorial
Create a file and call it index.php. Put the following code into the file.<!DOCTYPE html> <html> <head> <title>Submit Form Using AJAX and jQuery</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> </head> <body> <input id="name" type="text" placeholder="Your Name"> <input id="email" type="text" placeholder="email"> <input id="submit" type="button" value="Submit"> <div id="display"></div><script> $(document).ready(function(){ $("#submit").click(function(){ var name = $("#name").val(); var email = $("#email").val(); var dataString = 'name1='+ name + '&email1='+ email; if(name==''||email=='') { $("#display").html("Please Fill All Fields"); } else { $.ajax({ type: "POST", url: "processor.php", data: dataString, cache: false, success: function(result){ $("#display").html(result); } }); } return false; }); }); </script> </body> </html>
Now create a file and call it processor.php and put the following code into the file.
<?php $name=$_POST['name1']; $email=$_POST['email1']; echo "Form Submitted Succesfully"; echo '<br/>'; echo $name; echo '<br/>'; echo $email; ?>