Home  >  Article  >  Backend Development  >  How to Persist Changes Made with jQuery UI Sortable to a Database?

How to Persist Changes Made with jQuery UI Sortable to a Database?

Linda Hamilton
Linda HamiltonOriginal
2024-11-05 16:27:02690browse

How to Persist Changes Made with jQuery UI Sortable to a Database?

jQuery UI Sortable: Persist Order Changes to a Database

When using the jQuery UI sortable function to allow users to rearrange elements, it's often desirable to save the new order to a database. Here's how to achieve this:

The jQuery UI sortable feature provides a serialize method for this purpose. It creates an array of elements using their IDs. For instance, a list like this:

<code class="html"><ul id="sortable">
  <li id="item-1"></li>
  <li id="item-2"></li>
  ...
</ul></code>

When the serialize method is triggered, it produces a POST query string like this:

item[]=1&item[]=2

Assuming each element's ID corresponds to the database ID, you can iterate through the POSTed array and update the elements' positions in the database.

Here's an example in PHP:

<code class="php">$i = 0;

foreach ($_POST['item'] as $value) {
  // Execute statement:
  // UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
  $i++;
}</code>

To initiate the serialization and order update upon change, use this jQuery code:

<code class="javascript">$('#element').sortable({
  axis: 'y',
  update: function (event, ui) {
    var data = $(this).sortable('serialize');

    // POST to server using $.post or $.ajax
    $.ajax({
      data: data,
      type: 'POST',
      url: '/your/url/here'
    });
  }
});</code>

This code creates a POST request with the updated order and sends it to the specified URL.

The above is the detailed content of How to Persist Changes Made with jQuery UI Sortable to a Database?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn