dzimi
dzimi

Reputation: 829

jquery ajax sortable pass data in object as key value after serialize

I am using jquery ui sortable to reorder a list via php, I get the ids like so:

var ids = $('#sort1').sortable('serialize');

It works fine when on update in the ajax call I pass the data in the ajax call like so:

data: ids

And then catch in inside my php script like so (notice singular id):

$getids = $_POST['id'];

All that works fine, however I want to pass the data inside an object because there are other things I want to pass along as well, but it does not seem to be working.

I tried:

data: {
    id: ids
},

then I get this php error:

 Warning: Invalid argument supplied for foreach() in C:\wamp\www\sortable\sort.php on line 8

And I also tried changing $getids = $_POST['id']; to $getids = $_POST['ids']; but then I get unidentifed index and also invalid argument error.

How can I pass the ids inside an object as key value pair?

EDIT:

the foreach code

$count = 1;
foreach ($getids as $key => $id) {
    $q = "UPDATE titles SET sorting='$count', parent_id='1' WHERE id='$id'";
    $r = mysqli_query($dbc, $q);

    if ($r) {
        echo 'done <br>';
    } else {
        echo 'problem <br>' . mysqli_error($dbc);
    }
    $count++;
}

Upvotes: 1

Views: 639

Answers (1)

Embluk
Embluk

Reputation: 21

I had this issue and came across this post, as it doesn't include any code to solve the issue. I finally found a solution that worked for me...

In my Ajax request I converted my sortable UI to an array using the following:

var data = $(this).sortable('toArray');

Then the Ajax request was sent the following way:

data: { sectiononelink: data, currentUserID: user_id },

Then because the sortable to array function gave me a string such as sectionone-asectionone-bsectionone-csectionone-d etc... I only wanted the letters after the "sectionone-" part of the string as I was looking to order a list in my html using the letters a - z.

In my PHP I used a foreach loop which contained:

$profileLinkOrder = "";

foreach($_POST['sectiononelink'] as $value)
{
    $profileLinkOrder .= substr(strstr($value, "-"), 1);
}

Then the variable $profileLinkOrder would come out like abcdefg etc... Depending on how I had my sortable UI list on my HTML page.

This worked for me so I hope someone else can use this to solve this problem. I could not find any other solutions on the web. Let me know if this helps.

Upvotes: 1

Related Questions