Creation of a sortable list with Ajax tutorial

One interesting Web 2.0 effect is the sortable list, and we are going to make one in less than five minutes thanks to Prototype and script.aculo.us libraries.

Prototype is a JavaScript Framework that aims to ease development of dynamic web applications and can be downloaded here, while script.aculo.us (scriptaculous from now on) provides you with easy-to-use, cross-browser user interface JavaScript libraries to make your web sites and web applications fly and can be downloaded here.

This tutorial is based on zen of shen’s pseudocode found at script.aculo.us Ajax Sortable Lists Tutorial.

This tutorial will show real code and a step by step guide through MySql, php and Ajax coding in order to create your sortable list.

Of course your hosting plan must allow you to use php and MySql, so refer to your hosting provider if you don’t know if your web space supports those features.

MYSQL

First we need to work on the database to create the table that will store our list. I made the simplest table ever, because it’s just an example, but you can add as many columns as you want, in order to fit the table to your needs.

My table only has three fields: the primary key id, the name of the list element color and the core column, the one where you will save the order of the elements, called, in a lack of creativity, color_order.

CREATE TABLE `sortable` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`color` TEXT NOT NULL ,
`color_order` INT NOT NULL 
) ENGINE = MYISAM ;

Once we have the table, let’s populate it. I am doing it directly with MySql, but again you are free to code your own application to populate it

INSERT INTO `sortable` ( `color` ) 
VALUES (
'Red'
), (
'Yellow'
), (
'Green'
), (
'Blue'
), (
'Black'
), (
'White'
), (
'Orange'
), (
'Purple'
)

Now the table looks like this one

and our MySql task is completed. Now, let’s write some php and html

PHP/HTML

$row[color]\n";
}

?>


	
		
		
		
	
	
		
Drag to sort your favourite colors

Lines 3-4: Connecting to the database. If you don’t know your username, password or database name, ask them to your hosting provider

Lines 6-8: Query to get all the colors ordered by their color order

Lines 10-13: Building the list from the result of the query just executed

Lines 19-20: Including Prototype and scriptaculous sources. Remember to include Prototype before Scriptaculous and also remember to change the path if you placed the scripts in a different location

Lines 21-25: Giving the list a touch of style

Lines 28-30: Displaying the list

Line 31: Creation of the div element to display Ajax output

Lines 32-38: Calling the Sortable.create function to initialize the sortable list. You can find more information about Sortable.create function in the scriptaculous wiki at this link

And the php/html is over.

Now, I should made the Ajax part. But it’s already made by Prototype thanks to the Ajax.Updater object, so I just have to make the sort.php script called in the Ajax.Updater object

You can find more information about the Ajax.Updater object in the API Docs pages at this link

So it’s basically php again, but I will call this part the Ajax part

AJAX

Create a file called sort.php and write:

 $varvalue) {
	$sql = "update sortable set color_order = ".mysql_real_escape_string($varname)." where id = ".mysql_real_escape_string($varvalue);
	$result = mysql_query($sql) or die(mysql_error());
}

echo "You just updated it on ".date("Y-m-d H:i:s");

?>

Lines 3-4: Connecting to the database, just like in the php/html part

Lines 6-9: Scanning all the sortlist array passed with POST method by the Sortable.create and the Ajax.Updater and updating the color_order column of the sortable table according to sortlist names and values

Line 11: displaying an output message.

And that’s it! Drag colors as you want, then reload the page in the iframe and the colors will be in the same position you just ordered… unless someone else changed their order while the page was reloading

That’s all… hope you will find it useful as I did.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers