In today’s tutorial, I’m going to show you, how to Pass Data with Ajax to a PHP file and process it. Using this method, you can retrieve data from a database, and run other PHP scripts using the values of the forms and fields.
For the sake of this tutorial, we’re going to create a small user registration page. Normally, when you create something like this, you create a form, and on submit the page reloads. Not this time. We will be using Ajax to collect and send the data from the forms to an PHP file, where we process it, and then return the results with Ajax.
Creating the HTML
<input type="text" name="uname" id="uname"> <input type="text" name="upass" id="upass"> <button id="button"> Submit </button> <div id="result"></div>
In the above code, we create two text inputs, a button and an empty div. We will process the values of the two fields, when the button is pressed, and the results will appear on the results div.
Getting and Passing Data with Ajax
First, we need to include jQuery into our document.
Now that we have the form, and jQuery included in our document, we need to store it’s values in 2 variables, ( val1 and val2 ) so then we can pass it to the PHP file to process it.
As you can see in the code above, we create a .click event. This means that when the button with the ID of #button is click, out function will run. Then we get the value of each text field and store it in val1 and val2.
After we have the values, we create an $.ajax method. This method has 4 parameters.
The type is the way we send out data to the php file. If we use POST then in the PHP file, we use $_POST[”] to get the value. If we use GET then we use $_GET
The URL is basically the file we want to send the data to. In our case it’s process.php
The data store our data. in our case, uname: val1. This means that if we use $_POST[‘uname’] in the PHP file, we will get the value of the val1 which is what the first text field contains.
And then, Success is what will happen if all this succeeded. In this case, it will return what was displayed on in PHP file.
Creating the PHP file
In the process.php we will have 3-4 lines. the first two will get the values, of the fields, which were passed through, uname:val1 and upass:val2. And as I mentioned above, we have POST as type, so we will use $_POST to get the values.
<?php $text1 = $_POST['uname']; $text2 = $_POST['upass']; echo $text1 ; echo '<br/>'; echo $text2; ?>
And then we echo the value of the first and second field. This is what will our “success” will return. Of course, you can go much further then this. This is just an example of how it works.
If you enjoyed this tutorial and learned something from it, please consider sharing it with our friends and followers! Also like to my facebook page to get more awesome tutorial each week!