jQuery Sort and saving to database

Tutorials No Comments


When we used to sort elements we had to refresh web page for every change. Since javasrcipt and jQuery we can now do that dynamiclly. In this tutorial I will show you just how to do that. It is even more useful when you combine with it databases in which order of elements is crucial. In our example following table with name jquerysort will be used:

id text sort
1 some text 1
2 some text 2
3 some txt…. 3


We will use two files. First file will call the second one each time element is moved. Entries in second file update MySql table each time that happens. First file will be named sort.php.

First thing we have to do is include links to jQuery in < head > tag.

[amazon_carousel widget_type=”SearchAndAdd” width=600″ height=”200″ title=”” market_place=”US” shuffle_products=”True” show_border=”False” keywords=”jquery” browse_node=”” search_index=”Books” /]

In head part of html document we also have to include call to jQuery function that happens each time element is moved.

What we need now is a connection with our database so we can display results.

$connection = mysql_connect(‘localhost’, ‘username’ , ‘password’) or die(mysql_error());
$selection = mysql_select_db(‘db name’, $connection);

Get the results from database so they are available for sort that we are going to perform later on.

< ?php $query = “SELECT * FROM jquerysort ORDER BY sort ASC”; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { ?>

  • < ?php echo $row[‘id’] . “. ” . $row[‘text’];?>

< ?php } ?>

Finally we can display the table. Tag < li id=ID…> is crucial since we will write entry ID into it. Without it there is no way to know what to sort.

id=”recordsArray_< ?php echo $row[‘id’]; ?>”;

First file is now finished and it is time to code up the second one. We will name it UpdateDB.php (make sure name is the same as in jQuery call). First we will write in parameters that we got in previous steps.

$action = mysql_real_escape_string($_POST[‘action’]);
$updateRecordsArray = $_POST[‘recordsArray’];

We can now update our database with new values. A loop will iterate through all acquired values from first file and update our table. If there is any errors while updating we will fetch them.

foreach ($updateRecordsArray as $recordIDValue) {
$query = “UPDATE jquerysort SET sort = “.$listingCounter.” WHERE Id=”.$recordIDValue;
mysql_query($query) or die(‘Error, insert query failed’);
$listingCounter = $listingCounter + 1;

As a final step we will display a result in right column.

echo ‘

//Write new array
echo ‘

echo ‘Even if page is refreshed settings will remain since they are written in our database.’;

For more advanced guides check out learnyhub.com.

Thank you for reading this tutorial. Similar sorting is implemented in our Wordress Accordion Banner plugin.

We really appreciate you for visiting PremiumCoding and reading this article! Now you might also want to check out our Themes here.