Home > Backend Development > PHP Tutorial > 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
Release: 2024-11-05 16:27:02
Original
799 people have browsed it

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>
Copy after login

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

item[]=1&item[]=2
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template