• RSS
  • Print this article!
  • Digg
  • del.icio.us
  • DZone
  • Facebook
  • Mixx
  • Google Bookmarks
  • Design Float
  • Reddit
  • StumbleUpon
  • Technorati
  • Live
  • TwitThis
Home > Ajax, Front End Development, HTML, How to, Javascript, PHP > Beginners Guide to jQuery Sorting Part 2

Beginners Guide to jQuery Sorting Part 2

September 3rd, 2009

In the last tutorial we covered how to reorder a list by dragging and dropping.  In this tutorial we will show how to save the order of the list via Ajax.

Where We Left Off

We should be at a point where we now know how to reorder a list.  If you haven’t read the previous tutorial or aren’t certain on how to reorder lists in jQuery, I encourage you to check out Beginners Guide to jQuery Sorting part 1.

Here is the code from the previous post:

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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html lang="en">
<head>
    <title>jQuery UI Sortable - Drop placeholder</title>
   
     

    <style type="text/css">
        body{
            background-color: #111;
            color:white;
            font-family: Arial, "MS Trebuchet", sans-serif;
        }
        #sortable {
            list-style-type: none;
            margin: 0;
            padding: 0;
            width:300px
           
        }
        #sortable li {
            margin: 0 5px 5px 5px;
            padding: 5px 20px;
            font-size: 1.2em;
            height: 1.5em;
            background-color: #678;
            cursor:pointer;
           
        }
        #sortable li.highlight {
            height: 1.5em;
            line-height: 1.2em;
            background-color: #036;
            background-image: none;
            border:none;
        }
    </style>
   
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.core.js"></script>
    <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.sortable.js"></script>
    <script type="text/javascript">
    $(function() {
        $("#sortable").sortable({
            placeholder: 'highlight'
        });
        $("#sortable").disableSelection();
    });
    </script>
</head>
<body>

<ul id="sortable">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
</ul>


</body>
</html>

 

What We’re Building

This time around we’re just going to take the current order of the list and save it to the database for future use.

image

 

Reworking the List

Previously we had a simple HTML un-ordered list.  This time we’re going to make it a little more complicated, with good reason of course.  In order to view the updates we make to the database, we first have to have a list  pulling from the database.  For this we will be using PHP and MySQL.

First we’re going to create a file called db.php.  In this file we’re going to do two things.  First connect to the database, and second select all the items from the database and create a list from them.  I’m not going to go into too much detail with the connection info.  If you want a little refresher, we went into more depth in our Beginners Guide to Using Ajax with jQuery post.

Here is the PHP code for connecting to the database:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php

//Connection Info
$username="root";
$password="";
$host="localhost";
$database = "DragDrop";


//Connect to database
$mysqli =  new mysqli($host, $username, $password, $database);

// check connection
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

?>

 

I guess at this point it might be helpful to see what the database looks like.  We have 3 columns:

  •  itemID (unique identifier),
  • content (the text inside our list)
  • Order (keep track of the order)

database table

 

 

Now we’ll create a function that selects all the items from the database and outputs an un-ordered list.

Here is the 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
//Display a list of all entries
function displayAll (){
    global $mysqli;
   
    //Get all Entries
    if ($result = $mysqli->query("SELECT * FROM `Items` ORDER BY `Order` ASC")) {
           
            //start list
            $returnValue = "<ul id='sortable'>";
           
            while ($row = $result->fetch_array())
            {
                //add a new list item each iteration
                $returnValue .= "<li id='item_".htmlentities($row['itemID'])."'>".htmlentities($row['content'])."</li>";
            }
            //close list
            $returnValue .= "<ul>";
           
            //display list
            echo $returnValue;
   
        /* free result set */
        $result->close();
    }
}

 

First we query the database with the mysqli object we created when we connected to the database.  If it returns results without errors then we can go ahead with making our list. 

Making the list isn’t too hard, we’re simply creating a variable that holds our list.  We then cycle through all of the items returned from the database and add it to the end of our variable.  After we have all the info in our variable, we display it for the world to see.  One special note, you’ll see that we are giving each <li> an id.  We’re going to use this when we get to the Ajax portion of the tutorial.  For now just know that the id is required.

 

display all function

 

The New HTML

Now that we have our db.php file ready to go, we can now make use of it in our main file.

First off we’re going to import the file to use it.  At the very top we’ll just put:

1
<?php require("db.php"); ?>

 

Now we can use the function displayAll() that we just created.  We’ll be replacing the un-ordered list with this function.  When the page is processed, the function will pull the data from the database and output a brand spankin’ new list.  Pretty sweet huh.

1
2
3
4
5
6
7
8
9
10
<body>
<?php

//Displays the list.

displayAll();

?>

</body>

 

The jQuery

The jQuery changed a bit.  We’re adding a new update parameter to the sortable function.  This will be called whenever the order has been changed.

In the update function we’ll be doing 3 things.

  • Prepping the info to be sent via Ajax
  • Send the info via Ajax
  • Display the new updated list

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
$(function() {
    $("#sortable").sortable({
        placeholder: 'highlight',
       
        //NEW----Called when order is changed
        update: function() {
           
            //Prep the list order for transfer
            var listOrder = $(this).sortable("serialize");
           
            //send info to our php file.
            $.post("update.php", listOrder, function(response){
               
                //update the list with the new list.
                $("sortable").html(response);
            });
        }
    });
   
    $("#sortable").disableSelection();
});

 

serialize order

 

Prepping the Info

First thing we tackle is prepping the info by serializing it.  This just means that we’re taking the order of the list and preparing them in a way that they can be attached to a url.(e.g. www.domain.com?serialized=data )  For this serialize function to work we have to create ids for our list items in a particular way.  If I want an array called “item”  then I would give my li tags an id of item_1, item_2, item_3, etc. The serialize function will take the text before the underscore as the array name, and the number after as it’s value.  So a list with ids of item_1, item_2 would be serialized to item[]=1&item[]=2 .   When we created the function displayAll() we took this into consideration, and put the items ID value from the database after the underscore so we can reference it later.

 

Send Info

Next comes the Ajax.  We’re going to use the post function.  We simply have to give it a url, any data we want to send to the url and the function we want to call when we receive something back from the url.

 

Display New List

The function that handles the response simply just switches out the list’s HTML with the new HTML.

 

Updating the Database

The first thing we’re going to do is create a file called update.php.  This is the file that will be called by the Ajax.  In this file a couple of things are going to happen.

  • Get the array sent in by the Ajax
  • Cycle through each item in the array
  • Update the database with the new value
  • Display a new list

Here is the 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
51
52
53
54
55
56
57
<?php

//Get the Array from Ajax
//Make sure it is an array.
if (is_array($_POST['item'])){
    $items = $_POST['item'];
}else{
    $items = "";
}



if ($items != ""){
   
//Connect to database.
require 'db.php';  

 
    //Cycle through Array.
    for ($i=0; $i < count($items); $i++) {
   
        //Make sure the value of the item is numeric.
        if (is_numeric($items[$i])){
            $id = $items[$i];
        }else{
            die("Invalid ID");
        }
       
       
        //Set the database order to match the order of the array.
        $query = "UPDATE `Items` SET `Order` = " . $i . " WHERE `itemID` = " . $items[$i];
       
        $mysqli->query($query) or die('Error, insert query failed');
       
       
       
    }
   
    /* Display a new list */
    if ($result = $mysqli->query("SELECT * FROM `Items` ORDER BY `Order` ASC")) {
           
            $returnValue = "";
            while ($row = $result->fetch_array())
            {
                $returnValue .= "<li id='item_".htmlentities($row['itemID'])."'>".htmlentities($row['content'])."</li>";
            }
           
            echo $returnValue;
   
        /* free result set */
        $result->close();
    }
   
}


?>

 

Get the Array from Ajax

Since we used the post method in our jQuery, PHP’s $_POST variable will be populated by what we pasted in.  In our case it was the item array. It’s always good practice to make sure you’ll be receiving what you’re expecting.  In this case we’re expecting an array, so we check and make sure it is an array.

 

Cycle through the Array

After we’re sure we have an array on our hands, we cycle through each element in the array.  For each element we’re going to check and make sure the value is a number.  If we didn’t malicious users could pass in some harmful stuff.

 

Update the Database

After we have verified that array’s value is a number, we then pass it into our SQL statement.  The array is ordered in the same manner as the list was.  So the first item in the array is also the first item in the list.  The SQL will  then set the Order of the item to where it is in the array.

 

Display a New List

The code for this is pretty well the same as displayAll().  The only difference is that we’re leaving the <ul></ul> off, as these will already be in place, and we’re just replacing the innards.

 

That’s IT

That’s pretty well it.  Now we have our initial code that display’s our list.  Then our jQuery that passes on the order of the list via AJAX.  Then our update PHP file that checks to make sure the values are good, and passes them to the database.  After all that it passes the new list back to the jQuery to display.  Voila!

db.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
<?php
//Connection Info
$username="root";
$password="";
$host="localhost";
$database = "DragDrop";


//Connect to database
$mysqli =  new mysqli($host, $username, $password, $database);

// check connection
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

//Display a list of all entries
function displayAll (){
    global $mysqli;
   
    //Get all Entries
    if ($result = $mysqli->query("SELECT * FROM `Items` ORDER BY `Order` ASC")) {
           
            //start list
            $returnValue = "<ul id='sortable'>";
           
            while ($row = $result->fetch_array())
            {
                //add a new list item each iteration
                $returnValue .= "<li id='item_".htmlentities($row['itemID'])."'>".htmlentities($row['content'])."</li>";
            }
            //close list
            $returnValue .= "<ul>";
           
            //display list
            echo $returnValue;
   
        /* free result set */
        $result->close();
    }
}

?>

 

Here is the HTML / jQuery / 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
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
<?php require("db.php"); ?>

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

<html lang="en">
<head>
    <title>jQuery UI Sortable - Drop placeholder</title>

    <style type="text/css">
        body{
            background-color: #111;
            color:white;
            font-family: Arial, "MS Trebuchet", sans-serif;
        }
        #sortable {
            list-style-type: none;
            margin: 0;
            padding: 0;
            width:300px
           
        }
        #sortable li {
            margin: 0 5px 5px 5px;
            padding: 5px 20px;
            font-size: 1.2em;
            height: 1.5em;
            background-color: #678;
            cursor:pointer;
           
        }
        #sortable li.highlight {
            height: 1.5em;
            line-height: 1.2em;
            background-color: #036;
            background-image: none;
            border:none;
        }
    </style>
   
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.core.js"></script>
    <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.sortable.js"></script>
    <script type="text/javascript">
    $(function() {
        $("#sortable").sortable({
            placeholder: 'highlight',
           
            //NEW----Called when order is changed
            update: function() {
               
                //Prep the list order for transfer
                var listOrder = $(this).sortable("serialize");
               
                //send info to our php file.
                $.post("update.php", listOrder, function(response){
                   
                    //update the list with the new list.
                    $("sortable").html(response);
                });
            }
        });
        $("#sortable").disableSelection();
    });
    </script>
</head>
<body>
<?php

//Displays the list.

displayAll();

?>

</body>
</html>

 

update.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
51
52
53
54
55
56
57
<?php

//Get the Array from Ajax
//Make sure it is an array.
if (is_array($_POST['item'])){
    $items = $_POST['item'];
}else{
    $items = "";
}



if ($items != ""){
   
//Connect to database.
require 'db.php';  

 
    //Cycle through Array.
    for ($i=0; $i < count($items); $i++) {
   
        //Make sure the value of the item is numeric.
        if (is_numeric($items[$i])){
            $id = $items[$i];
        }else{
            die("Invalid ID");
        }
       
       
        //Set the database order to match the order of the array.
        $query = "UPDATE `Items` SET `Order` = " . $i . " WHERE `itemID` = " . $items[$i];
       
        $mysqli->query($query) or die('Error, insert query failed');
       
       
       
    }
   
    /* Display a new list */
    if ($result = $mysqli->query("SELECT * FROM `Items` ORDER BY `Order` ASC")) {
           
            $returnValue = "";
            while ($row = $result->fetch_array())
            {
                $returnValue .= "<li id='item_".htmlentities($row['itemID'])."'>".htmlentities($row['content'])."</li>";
            }
           
            echo $returnValue;
   
        /* free result set */
        $result->close();
    }
   
}


?>

 

  • RSS
  • Print this article!
  • Digg
  • del.icio.us
  • DZone
  • Facebook
  • Mixx
  • Google Bookmarks
  • Design Float
  • Reddit
  • StumbleUpon
  • Technorati
  • Live
  • TwitThis
  1. September 4th, 2009 at 06:11 | #1

    Thanks so much for this. I’m building an estate agent’s website at the moment and they want to be able to change picture orders on the fly – this will be perfect!

  2. Anton
    September 17th, 2009 at 09:20 | #2

    Great guide!!!! Thank you very much!!!!!

  3. Anton
    September 18th, 2009 at 02:20 | #3

    I have a one question. How yo create sorting with 2 columns?

Comments are closed.