Home > Ajax, Back End, Front End Development, How to, Javascript, PHP > Beginners Guide to Using AJAX with jQuery

Beginners Guide to Using AJAX with jQuery

July 29th, 2009


AJAX offers users a seamless way to work with your interface, no waiting for whole pages to load.  jQuery has a set of tools to make it super simple to implement. We will walk you through how to use jQuery to connect to PHP so you can step up your user interface.

 

What is AJAX

AJAX is a short hand for asynchronous JavaScript and XML.  Which plainly means that instead of waiting for the whole page to load, you can load only what you need to.  So if you only need to update one small text part of your site, you don’t have to worry about loading everything else on that page.  A vast majority of sites use this technology now.  Probably one of the most popular uses is an auto complete feature for the search box at Google and Yahoo.

 

What We Will Be Building

There are several things that we could build, but we’re just going to keep it simple for this example.  We’re going to create a simple text field that when you type in anything it gets sent to the server via jQuery.  In return the server will append some text and send it back to jQuery.

 

Getting Start

The HTML is pretty simple.  We just need an input text and a div with an id so jQuery can input the text when it gets it back from the server. We’ll also need to import the jQuery library.

Here is the HTML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>Ajax With Jquery</title>
   
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
</head>
   

<body>
   
    <label for="txtValue">Enter a value : </label>
    <input type="text" name="txtValue" value="" id="txtValue">
   
    <div id="display"></div>
   
</body>
</html>

 

The jQuery

Now we have the framework down we can get started on the jQuery.  The first thing we are going to do is create a key up event for our input text box once the page loads.  Once a user types a character in the text box it will call a function that handles the AJAX.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//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());  
       
    });
   
});

 

Now here is the magic. We’re going to create the function that handles the AJAX.  The function will have one argument; this will be the text from the text box.  There are several ways to use AJAX with jQuery.  We are going to use the post method, but I encourage you to have a look on jQuery’s website to check out the other methods.  We’ll be using 4 arguments with the post method, but only the first one is required.

Post Method Arguments:

  1. Your file on the server, in our case, a PHP file.
  2. The values you want to pass to the server.  These will be sent using the POST request.
  3. The function that is called when the server responds. In our case this is where we use jQuery to populate the div with the info we got back from the server.
  4. This is how the data will be organized.  In our case we’ll be using JSON.

Here is the jQuery AJAX Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 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"
    );
   
}

 

The PHP

There isn’t much to the PHP file.  We simply get the POST variables, make sure our output is JSON encoded, then output what we want to return to our jQuery.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?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)); 

?>

 

Bringing it All Together

That wasn’t all the difficult was it.  This is the beginning of making a auto complete search box.  The biggest thing you would have to do to finish it is adjust the PHP so it searches your data, and outputs the appropriate results.  Perhaps in another tutorial we’ll handle that.  For now here is the code all together:

HTML / jQuery :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>Ajax With Jquery</title>
   
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8">

        $(document).ready(function(){
            $('#txtValue').keyup(function(){
                sendValue($(this).val());  
               
            });
           
        });
        function sendValue(str){
            $.post("ajax.php",{ sendValue: str },
            function(data){
                $('#display').html(data.returnValue);
            }, "json");
           
        }
       
    </script>
</head>
   

<body>
   
    <label for="txtValue">Enter a value : </label>
    <input type="text" name="txtValue" value="" id="txtValue">
   
    <div id="display"></div>
   
</body>
</html>

PHP :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?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)); 

?>

 

 




Top