JavaScript
Article

jQuery with Ajax and PHP Basics

By Sam Deering

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.

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">









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.

< ?php
//Get Post Variables. The name is the same as
//what was in the object that was sent in the jQuery

if (isset($_POST['sendValue'])){
 $value = $_POST['sendValue'];
}else{
 $value = "";
}
//Because we want to use json, we have to place things in an array and encode it for json.
//This will give us a nice javascript object on the front side.
echo json_encode(array("returnValue"=>"This is returned from PHP : ".$value));
?>

Altogether

Here is the result if all were combined together.

jQuery/HTML code:

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">










PHP:

< ?php

//Get Post Variables. The name is the same as
//what was in the object that was sent in the jQuery
if (isset($_POST['sendValue'])){
 $value = $_POST['sendValue'];
}else{
 $value = "";
}

//Because we want to use json, we have to place things in an array and encode it for json.
//This will give us a nice javascript object on the front side.
echo json_encode(array("returnValue"=>"This is returned from PHP : ".$value));
?>

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

No Reader comments

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.