• RSS
  • Print this article!
  • Digg
  • del.icio.us
  • DZone
  • Facebook
  • Mixx
  • Google Bookmarks
  • Design Float
  • Reddit
  • StumbleUpon
  • Technorati
  • Live
  • TwitThis
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)); 

?>

 

 

  • RSS
  • Print this article!
  • Digg
  • del.icio.us
  • DZone
  • Facebook
  • Mixx
  • Google Bookmarks
  • Design Float
  • Reddit
  • StumbleUpon
  • Technorati
  • Live
  • TwitThis
  1. panchicore
    July 30th, 2009 at 23:33 | #1

    Is a very good-detailed explanation. :) Is this the way as some input fields counts the characters writed in them?, like twitter 140-characters limits?.

  2. July 31st, 2009 at 09:06 | #2

    You can do that strictly with JavaScript. No Ajax required. You just need to figure out the length of the String in the input box and subtract it from the max characters. So something like 140 – $(’#inputBox’).val().length;

  3. August 1st, 2009 at 17:50 | #3

    Thanks for the easy tutorial.

    But can you explain a bit more the data argument in the .post function? How would it look with multiple variables passed, for instance?

  4. August 2nd, 2009 at 00:35 | #4

    The data argument takes an object, so if you wanted to pass more than one argument you could do something like {item1:value1, item2:value2} . So just add more values and separate them by commas. In your PHP you can access the values by something like $_POST['value1'] and $_POST['value2'].

  5. August 2nd, 2009 at 22:32 | #5

    nice !!and so easy!

  6. eve
    August 24th, 2009 at 02:36 | #6

    i’m sorry but it didn’t work out for me…
    i’m already change the src to be

    but why isn’t it working in my localhost?
    Thx for the tuto anyway…

  7. August 24th, 2009 at 16:00 | #7

    Hey Eve, Unfortunately the comments box in wordpress kills code so I can’t see what you changed the src to. If you’d like you can send me an email via the contact form and I’d be more than happy to help you out.

  8. eve
    September 8th, 2009 at 02:52 | #8

    So sorry, guess it’s al my fault… >_< maybe it's becoz i just double click the .html file, so it didn't work… when i fix the link to http://localhost/... it works. Thx.

  9. Scott
    October 18th, 2009 at 08:26 | #9

    Hi, thank you so much for posting this. It’s an easy to follow but tremendously helpful tutorial. I’ve bookmarked the site :)

    One thing I was hoping you could help me on though. I’ve got the original call working, but I need to rebind the ajax call for the data returned in the original call. I’m fairly new to js and specifically jQuery, so any help would be really helpful. Here’s the link. It’s a test page.
    http://chshub.com/teacher/kents/discussion.asp?dId=1

    Thanks!

  10. Scott
    October 18th, 2009 at 09:46 | #10

    Woohoo! I think I figured it out, but it probably is the least elegant way to do it.

    In addition to calling the post function on document.ready, I added it to the returned function in addition to posting the returned value. When I first did it, I ended up with a thousand calls because it was doubling the calls I think because of the scope…I think…so I added the id of the returned html element to the call. If you have a second, let me know if I’m way off base, or if I’m doing something totally inappropriate…

    Thanks again for the post.

  11. October 19th, 2009 at 04:41 | #11

    Thanks for the tutorial.
    Its useful and easy. I’ll wait more from you.

  12. ajay
    November 18th, 2009 at 17:16 | #12

    Hello,

    thanks for the good tutorial which is easy to understand.
    I am trying to delay the unblock for 2 secs after i get the Ajax response. Can you see what i’m doing wrong here..

    function sendValue(str){
    $.post( “ajaxResponse.do”, { loanAmount: str },
    function(data){
    if (data.trim() == “false”) {
    document.getElementById(’ajaxMessage’).innerHTML = “Problem Updating the Loan Data”;
    setTimeout($.unblockUI, 2000); // this one works fine
    } else {
    // these two do not work but
    setTimeout($.unblockUI, 2000);
    setTimeout(location.href=”searchInit.do”, 2000);
    }
    }, “” );
    }

    thanks in advance..
    ajay

Comments are closed.