Home > Back End, CSS, Front End Development, Javascript, PHP > Beginners Guide to Using AJAX with jQuery Part 2

Beginners Guide to Using AJAX with jQuery Part 2

August 9th, 2009


In a previous tutorial we showed how to use AJAX with jQuery.. We created a simple input box that outputs info from the server after each character you type in.  In this tutorial we will take one step further and create an auto complete feature, much like Google or Yahoo’s  search box.

What we will be building

We’ll be creating an input box that when you type it checks out the database for any words that might match what you typed in.  The database I’ll be using is a dictionary I found on the net.  It seems to be missing quite a few words, but it’ll work for what we will be doing.

image

 

Getting Started

Since we’ll be starting where we left off in the tutorial Beginners Guide to using AJAX with jQuery it might be a good idea to pick up the original files if you want build it out yourself.  There are two files.  One being the HTML file with the jQuery and the other being the PHP file that process the AJAX request. 

Here is a look at where we left off:

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
<?php


if (isset($_POST['sendValue'])){
    $value = $_POST['sendValue'];  
}else{
    $value = "";
}

echo json_encode(array("returnValue"=>"This is returned from PHP : ".$value));

?>

 

The Database

The database we’ll be creating consists of one table called “Words”. In that table there is only one column called “Word”.  Here is the CSV file that I used to populate the database we’ll be using. 

The first thing we’re going to do is connect to the database.

PHP:

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
if (isset($_POST['sendToValue'])){
    $value = mysql_escape_string($_POST['sendToValue']);   
}else{
    $value = "";
}

if (isset($value) && strlen($value) > 0){
   
    //The Connection Info
    $username="root";
    $password="";
    $host="localhost";
    $database = "dictionary";
   
    //Connecting to the database
    $mysqli =  new mysqli($host, $username, $password, $database);
   
    // Make sure we connected okay
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
}else{
    // If there is no value send empty value back to jQuery.
    echo json_encode(array("empty"=>true));
}

 

Getting Results from the Database

After connecting to the database, our goal now is to pull words from the database that match what was passed to the PHP via AJAX.   The SQL we’ll be using to query the database isn’t too difficult.

1
SELECT * FROM `Words` WHERE `Word` LIKE '$value%' LIMIT 5

The SQL statement simply means select 5 rows from the “Words” table where the column “Word”  starts with whichever value we pass in. $value is a PHP variable, and % is a wild card meaning any value.

Here is the PHP to Query the Database:

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
$returnValue = ""; // define variable that will be sent back to jQuery 
   
// Query the database
if ($result = $mysqli->query("SELECT * FROM `Words` WHERE `Word` LIKE '$value%' LIMIT 5 ")) {
   
    //If there are some results then...
    if ($result->num_rows > 0){
       
        // create unordered list with results
        $returnValue .= "<ul>";
       
        //step through each result.
        while ($row = $result->fetch_array())
        {
            // $row['Word'] references the "Word" column of the result.
            // htmlentities is good security practice. Make sure there is no harmful
            // JavaScript being outputed.
            $returnValue .= "<li>".htmlentities($row['Word'])."</li>";
        }
        $returnValue .= "</ul>";
       
        //Send information back to jQuery.
        echo json_encode(array("returnFromValue"=>$returnValue));
    }else{
        // If there are no results send empty value back to jQuery.
        echo json_encode(array("empty"=>true));
    }

    /* free result set */
    $result->close();
}

 

After we get the results back, we’ll want to output any results we get back as an unordered list. If there aren’t any results we’ll output an empty value so we know we didn’t get any results back.

 

Let the Beautification Begin

As of right now we should have a list of words that show up after each character we type in.  Now we just have to beautify it a bit.  We’ll have to make it so that the list doesn’t appear until the user starts typing, and disappear after the input box loses focus.  We’ll also make it so that when you click on one of the words in the list it will populate the input box with that value.  Additionally we should handle when a user presses the down or up button, but we’re not going to for the sake of keeping things simple for this tutorial.

Here is the 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
$(document).ready(function(){
   
    $('#txtValue')
    // when a key is pressed send value to php
    .keyup(function(){
        sendValue($(this).val());
    })
    // hide auto complete list when input loses focus
    .blur(function(){
        $('#display').slideUp(500);
       
    });

});

//Send and recieve values from PHP
function sendValue(str){
    $.post("ajax.php", { sendToValue: str },
    function(data){
        if (!data.empty){
             $('#display').html(data.returnFromValue);
             $('#display').show();
             
             //Sets up auto complete list mouse events.
            init();
           
        }else{
            $('#display').html("")
            $('#display').hide();
           
            //Cleans up list's mouse events
            cleanUp();
        }
       
    }, "json");
}

//Setup list's click and hover mouse events.
function init(){
    cleanUp();
    $('#display li')
    .click(clicked)
    .hover(toggleOver,toggleOver);
}

//unsets list's mouse events.
function cleanUp (){
    $('#display li').unbind("click");
    $('#display li').unbind('mouseenter').unbind('mouseleave');
}

// list's click event handler.  Puts selected text into input text box.
function clicked(){
    $('#txtValue').val($(this).text());
}

// highlight list item when user rolls over it.
function toggleOver(){
    $(this).toggleClass("over");
}

 

CSS:

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
body{
    background-color:#111;
    color:#999;
    font-family: Arial, "MS Trebuchet", sans-serif;
}
/* Put list under input box.*/
#display{
    background-color:#333333;
    color:white;
    left:100px;
    padding:10px 0 10px 5px;
    position:relative;
    width:145px;
    display:none;
}
#display ul{
    list-style:none;
    margin:0;
    padding:0;
}

/*Give list item hand pointer*/
#display li{
    cursor: pointer;
}

/* Roll over state of list item*/
.over{
    background-color:#6484CE;
}

 

Bringing it All Together

That’s all the code we’ll need for now.  The auto complete feature can definitely be improved, but hopefully this tutorial showed a useful use of AJAX with jQuery.

Here is all the code together:

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<!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>
<style type="text/css" media="screen">
    body{
        background-color:#111;
        color:#999;
        font-family: Arial, "MS Trebuchet", sans-serif;
    }
    #display{
        background-color:#333333;
        color:white;
        left:100px;
        padding:10px 0 10px 5px;
        position:relative;
        width:145px;
        display:none;
    }
    #display ul{
        list-style:none;
        margin:0;
        padding:0;
    }
    #display li{
        cursor: pointer;
    }
    .over{
        background-color:#6484CE;
    }

</style>

<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());
        })
        .blur(function(){
            $('#display').slideUp(500);
           
        });

    });
   
    function sendValue(str){
        $.post("ajax.php", { sendToValue: str },
        function(data){
            if (!data.empty){
                 $('#display').html(data.returnFromValue);
                 $('#display').show();
                init();
               
            }else{
                $('#display').html("")
                $('#display').hide();
                cleanUp();
            }
           
        }, "json");
    }
   
    function init(){
        cleanUp();
        $('#display li')
        .click(clicked)
        .hover(toggleOver,toggleOver);
    }
   
    function cleanUp (){
        $('#display li').unbind("click");
        $('#display li').unbind('mouseenter').unbind('mouseleave');
    }
   
    function clicked(){
        $('#txtValue').val($(this).text());
    }
   
    function toggleOver(){
        $(this).toggleClass("over");
    }

   

</script>
</head>
   

<body>
    <p>On keyup this text box sends a request to PHP and a value is returned.</p>
    <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
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php

if (isset($_POST['sendToValue'])){
    $value = mysql_escape_string($_POST['sendToValue']);   
}else{
    $value = "";
}

$returnValue = "";


if (isset($value) && strlen($value) > 0){
   
    $username="root";
    $password="";
    $host="localhost";
    $database = "dictionary";
   
    $mysqli =  new mysqli($host, $username, $password, $database);
   
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
   
    if ($result = $mysqli->query("SELECT * FROM `Words` WHERE `Word` LIKE '$value%' LIMIT 5 ")) {
        if ($result->num_rows > 0){
            $returnValue .= "<ul>";
            while ($row = $result->fetch_array())
            {
                $returnValue .= "<li>".htmlentities($row['Word'])."</li>";
            }
            $returnValue .= "</ul>";
            echo json_encode(array("returnFromValue"=>$returnValue));
        }else{
            echo json_encode(array("empty"=>true));
        }
   

        /* free result set */
        $result->close();
    }
   
   
}else{
    echo json_encode(array("empty"=>true));
}
   
?>

 




Top