Home arrow JavaScript arrow Page 4 - Sorting the Easy Way

Sorting the Easy Way

I bet most of us have developed an application where a list of products were retrieved from a database and shown in a table with their name, price and code. So we placed a cute little icon near each column's header that linked to the search page with a flag in the URL to let it know we wanted the results ordered by name or price. The search script kindly did its job, adding the ORDER BY clause, and the ordered results were shown to the user. Obviously this method works, but there is a problem: Why must we bother the server again to retrieve the same results that are now held in the browser, only in a different order? This article will show you the quickest way to order your database results, via JavaScript, with some work in PHP.

Author Info:
By: Alf A. Pedersen
Rating: 4 stars4 stars4 stars4 stars4 stars / 10
March 17, 2004
  1. · Sorting the Easy Way
  2. · The Basic Code
  3. · We Love INNERHTML!
  4. · See What We've Done...
  5. · PHP Sorting

print this article

Sorting the Easy Way - See What We've Done...
(Page 4 of 5 )

We have this PHP array $prices that holds the prices of our products.  The key is the product's ID and its value is the price of the product. We sort it numerically, and store its indexes (now ordered by price) in a JS array. If we reverse it, we can store its reverse ordered indexes in another JS array. This is how the JS arrays look:

var ordPrice=new Array(10,1,9,2,5,4,6,3,7,8);
var ordPriceInv
=new Array(8,7,3,6,4,5,2,9,1,10);

Then we have the JS order function, which accepts one parameter called field. This parameter is the name of the JS array we'll use to reorder the rows of our table. The function obtains the ID of the first product (following the new order), grabs the contents of its row and appends them to the output variable.

Notice that since the innerHTML property stores only the contents of the TR tags, we must append manually the TR tags to the output variable, and that means setting the ID too. Once we have the HTML code of the new table, we just send it to the innerHTML property of the content div, which displays it immediately.  Now tell me, don't you love innerHTML?  I personally think it's the best thing since sliced bread!

I Need More!

Yes! Once you see how fast this code sorts rows in a table you just have to use it with the other columns. So, let's see the final example, a little bit more optimized to make your life easier:

//The function that sorts any array and generates the JS output
function gen_ord_array($name,$variable, $flag)
 $out="var $name=new Array(";
 asort($variable, $flag);
 reset ($variable);
 while (list ($key, $val) = each ($variable))
  $out.= "$key,";

 //Now for the inverse JS array
 $out.="var $name"."Inv=new Array(";
 $variable=array_reverse($variable, TRUE);
 reset ($variable);
 while (list ($key, $val) = each ($variable))
  $out.= "$key,";
return $out;
//Connect to the database
$conn=mysql_connect('localhost','root','') or die ('Sorry, no connection to database available :-(');
//Perform our query
$query='SELECT * FROM test.products';
if (!$res=mysql_query($query$conn))
die ('Sorry, query error');
//We populate the $output variable with the HTML code to generate the results table
//Now the headers have links to perform the sorting
//We'll keep the table header in another variable to save us time 
//in the JS function
$output_h='<table border="1" cellpadding="5"><tr style="font-weight:bold">'
$output_h.='<td><a href="#" onClick="order('ordName')">v</a>   NAME 
  <a href="#" onClick="order('
$output_h.='<td><a href="#" onClick="order('ordPrice')">v</a>   PRICE 
  <a href="#" onClick="order('
$output_h.='<td><a href="#" onClick="order('ordCode')">v</a>   CODE 
  <a href="#" onClick="order('
$output_h.='<td><a href="#" onClick="order('ordWeight')">v</a>  WEIGHT 
  <a href="#" onClick="order('
//We keep the number of results of the query, they will be 
//used in JavaScript
while ($a=mysql_fetch_row($res))
//Append the table row to our $output variable
 //Add this product to the sort arrays
//We now do the sorting of the arrays, and store them in a JS array
? >
<script language="
var num_results= <?=

//We output the array definitions
<?=$jsOutput? >
//This is the function that performs the actual sorting
function order (field)
 //This var will store the row number we are grabbing from the table
 var row_number=0;
 //We must generate again the table headers
 //Luckily, we already have them in the PHP 
$output_h variable
 //But we must escape the single quotes!!
 var out='<?=str_replace("'","\'",

 //The field variable is the name of the array we want to use to 
 //reorder our table 
 //We travel across it and grab the content of the row that has 
 //that ID, and append it to our out variable
 for (x=0;x<num_results;x++)
  eval ("
  eval ("
 //Finally, we set the content of the content div to our new table
<div id='content'>
$output? >

blog comments powered by Disqus

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials