jQuery with Ajax and PHP Basics
Ajax offers a great way to work with your interface, and no more waiting for the whole page to load. jQuery has a set of tools to make it simple to apply. This guide will help you to understand on how to use jQuery to connect to PHP.
AJAX Explained
Asynchronous JavaScript and XML (AJAX) is a very simple but useful server side scripting. Well known for its partial refresh of the page, you don’t have to refresh a whole web page just to see an update for a single small part of it. Large number of websites uses this now.
What we aim to build
Actually, there are many things that we could build, but we’re going to focus for its simplicity, we’re going to build basic stuffs.
We’re going to create a text field wherein you can type anything and it’ll be sent to the server via jQuery. The server will append some part of the text and sent it back to jQuery.
Start
This HTML code is pretty simple. All we need is an input text and as well as div with an id so jQuery can input the text when it returns back from the server. We also need the jQuery library.
Ajax With Jquery
It’s time for jQuery
First thing first, we need to create a simple key up event for our input text box when the page loads. Once a user types anything in the text box it’ll call a function that handles the AJAX.
//When Page Loads....
$(document).ready(function(){
// When the user finishes typing
// a character in the text box...
$('#txtValue').keyup(function(){
// Call the function to handle the AJAX.
// Pass the value of the text box to the function.
sendValue($(this).val());
});
});
Here is the magic part. We’re going to make a function that will handle the AJAX. That function will have a single argument; this will be the text from the text box. There are ways to use AJAX with jQuery. We are going to use the post method. We’ll be using 4 arguments though however the first one is required.
Post Method Arguments:
Your file on the server needed, in this tutorial it’s a PHP file.
The values that you want to pass over to the server using POST request.
The function will be called when the server responds.
The use of JSON to organize data.
jQuery AJAX Code:
// Function to handle ajax.
function sendValue(str){
// post(file, data, callback, type); (only "file" is required)
$.post(
"ajax.php", //Ajax file
{ sendValue: str }, // create an object will all values
//function that is called when server returns a value.
function(data){
$('#display').html(data.returnValue);
},
//How you want the data formated when it is returned from the server.
"json"
);
}
PHP
There’s not much to the PHP file. We simply get the POST variables. Just make sure that the output is JSON encoded and the output that we want to return to our jQuery.
"This is returned from PHP : ".$value));
?>
Altogether
Here is the result if all were combined together.
jQuery/HTML code:
Ajax With Jquery
PHP:
"This is returned from PHP : ".$value));
?>