We've written a PHP function that will take care of sorting the PHP arrays and generating the JS arrays. Its first parameter is the name of the array (this is the parameter we pass to the JS order function), the second is the array of data to sort, and the third a flag that indicates how the function will sort the array.
The table headers are kept in a variable so we don't have to re-write them again in the JS order() function, and links are added to the left and right of each column's header that call the JS order() function with the name of the array we want to use for the sorting.
In this article we've explored a nice example of how to sort the results of a database search in real time, giving the user a fast response which he/she will surely appreciate. It's not a lot of extra work to do, and I think it's really worth it.
By the way, I like the idea of PHP generating JS that generates HTML!Of course, there is a major problem with this trick. If the userís browser is too old and doesn't know what innerHTML is, we're in trouble. This trick should only be used if you detect that the userís browser can handle the innerHTML property. If it can't, the "older" approach I explained in the opening paragraph of the article could be used, maybe with a message to the user advising them to upgrade their browser.
This code was tested successfully on a P4 1'8 GHz 256 MB RAM with Windows 2000 Professional, Apache/1.3.27, MySQL 4.0.12, PHP 4.3.1 with the following browsers: Mozilla 1.4 and IE 6.0. It may not be 100% bug free, so I'd appreciate any feedback!
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.