2

i'm using the sortable javascript from http://farhadi.ir/projects/html5sortable/

The script works fine for me, but when i have no knowlidge of javascript it is a problem how to create the code to get back an array in php with the new order when you have moved a picture.

The code i use now:

<section>
<ul class="sortable grid">

    <?php
    $i=1; 

    foreach ($werkbladen as $werkblad) {

        $thumbnail = "../groepen/".$werkblad['werkblad'][path].$werkblad['werkblad'][thumbnail];

        echo '<li id = "'.$i.'"><img src="'.$thumbnail.'" width="139" height="181" /></li>';

        $i++;
    }
    ?>

</ul>
</section>

<script>
$('.sortable').sortable().bind('sortupdate', function() {

    //Triggered when the user stopped sorting and the DOM position has changed.

    // i will need here the code in javascript that creates a new array in php with the new order

});
</script>

i hope someone can help me out with this.

Maybe some more explaination will help too: This is how my session_array look like

Array
(
[0] => Array
    (
        [werkblad] => Array
            (
                [id] => 1105
                [database] => 1111
                [path] => groep12/1111
                [thumbnail] => mensen-kleding-03.jpg
                [bestand] => 
            )

    )

[1] => Array
    (
        [werkblad] => Array
            (
                [id] => 5639
                [database] => 1111
                [path] => groep12/1111/1111/
                [thumbnail] => mensen-kleding-1-minder-en-1-meer.jpg
                [bestand] => mensen-kleding-1-minder-en-1-meer.pdf
            )

    )

[2] => Array
    (
        [werkblad] => Array
            (
                [id] => 72
                [database] => 1111
                [path] => groep12/1111/
                [thumbnail] => passieve-woordenschat-02.jpg
                [bestand] => passieve-woordenschat-02.pdf
            )

    )

)

What i need is a array back with the sorted images. That array will be send to a php file that creates a pdf from it, so i will need all the information back as the original one.

Kind regards, Sietsko

  • You have to post back the variables to the php page. [Maybe this answer helps](http://stackoverflow.com/a/8191166/1449624). – A1rPun Apr 29 '15 at 08:46
  • I have read a lot off code but can't figure out how to do it in combination with my code. – Sietsko Bos Apr 29 '15 at 08:52
  • try using json as to bridge the two programing languages – madalinivascu Apr 29 '15 at 09:07
  • It depends what you want to do with the data. If you want to build a new view with the passed variable you can just call the php page with params and the page will be refreshed. Or you can do a simple AJAX request to the php page and store the variables in a database or something. – A1rPun Apr 29 '15 at 09:10
  • I need the new array in php in a new session and send it to another page where i paste the chosen images in the chosen order in a pdf. It works already to make the pdf but i only need the code to build a new array that i can send with php to the php file that creates the pdf. – Sietsko Bos Apr 29 '15 at 09:16
  • The documentation is very unclear about the params in sortupdate. I found [this fork](https://github.com/voidberg/html5sortable) (which is maintained) which explains it better. I will try to answer this for you today :) – A1rPun Apr 29 '15 at 13:03
  • I recommend using `str.join('|')` and then `explode('|', $_POST['yourstring'])` in PHP. If you need nested (up to some levels), you can use more symbols. If you are going to nest indefinitely, then JSON would be best. – gskema Apr 30 '15 at 08:27

2 Answers2

1

I always find that if I can avoid using JavaScript for a task, it often pays to do so. At least at the start, because it means your system can be used by more people. Having a script-disabled fallback is of benefit in terms of accessibility, and generally helps guide you in a way of building applications that stick to a reliable, easy to understand baseline.

I'm assuming that as you know PHP, you'll have a good understanding of HTML too.


Non-JavaScript solution

Basically all you'd need do as a simple solution is to render hidden inputs as part of the sortable markup. These inputs would have to have to be named with index-less array notation i.e. name="row[]" so that the HTML order is honored when the data is presented server-side.

The inputs would then be responsible for keeping the meaningful information stored within the HTML. You could PHP's serialize(), or json_encode() to deal with complex values, or — if you have access to the data as a set or list on the server-side i.e. in a database or session — it would be *preferable to just store unique IDs.

The hidden inputs would then be sorted along with the rest of the HTML.

*preferable : Why would storing just IDs be better? Not only will you be sending less data with simple IDs, less interference can occur if you end up with a malicious user. Someone who may attempt to post unwanted information to your server. You should always test and clean the data received from the outside world to your server, this is just easier to do when dealing with simple array key offsets — rather than complex data structures.


Slight changes to what you have already

In order for this to work you'll need to wrap your sortable list with a form tag and a **submit button, or at least some call-to-action that triggers the form's submit. Then when submit is called — without having to leverage JavaScript at all — the destination of the form will receive your data in the correct order.

<form id="sorted" action="destination.php" method="post">
<section>
<ul class="sortable grid">
  <?php
  $i=1; 
  foreach ($werkbladen as $werkblad) {
    $thumbnail = "../groepen/".$werkblad['werkblad'][path].$werkblad['werkblad'][thumbnail];
    /// I've used thumbnail as my stored data, but you use `$i` or anything you want really.
    $input = '<input type="hidden" name="row[]" value="' . $thumbnail . '" />';
    $image = '<img src="' . $thumbnail . '" width="139" height="181" />';
    echo '<li id="'.$i.'">' . $input . $image . </li>';
    $i++;
  }
  ?>
</ul>
</section>
</form>

**submit button : If I were to be generating a PDF, I wouldn't trigger its generation after every sort event. You would really want the user to request via a call-to-action because PDF generation is usually quite heavy process. Not to mention you waste bandwidth and processing time if the user hasn't finished with their ***ordering.

Then on the PHP side you'd get the row information using:

$_POST['row']; // <-- this should be a sorted array of thumbnail paths.

***ordering : True, you could put a timeout delay on the sortupdate event, so as not to trigger after every sort. But my reasons for implementing a call-to-action are not just based on minimizing the work your server has to do. It is just a good idea to implement a call-to-action by default, and then progressively hide it away for users that either don't want or need it.


Progressively enhanced

If you really did want an up-to-the-last-sort-interaction preview, then I would still implement the HTML only solution above, but progressively enhance with JavaScript to add the extra abilities. You can do this using an AJAX/$sortable solution that has already been commented about. However because you now have a form, you could use jQuery's .serialize() method. This is designed to take a form and generate the data that it would have submitted as a string of a name-value pairs. This "URL" string can then be POSTed or GETed back to the server in a number of ways.

$('.sortable').sortable().bind('sortupdate', function() {
  var data = jQuery('form#sorted').serialize();
  console.log(data);
  /// there are a number of ways you can use this data
  /// send it via AJAX, open a new tab, open a pop-up window,
  /// open a preview iframe... even encode it using semaphore
  /// and create a canvas animation of waving flags.
});
Community
  • 1
  • 1
Pebbl
  • 34,937
  • 6
  • 62
  • 64
  • Thanks Pebbl, i have chosen the php solution and changed a little and this really works great for me. Thank you very much for your help. And if i can reward you let me know how i can do this. No i don't send you money :-) – Sietsko Bos Apr 30 '15 at 14:16
0

You can do something like this in JavaScript:

var $sortable = $('.sortable');
$sortable.sortable().bind('sortupdate', function() {
    //Find all list items and retrieve the id's
    var ids = $sortable.find('li').map(function(idx, item){
        return item.id        
    }).toArray();
    //Post the array to the php page
    document.location.href = 'post.php?array=' + JSON.stringify(ids);
});

In your PHP file

json_decode($_GET['array'])

Check this fiddle to see the JavaScript in action:

jsfiddle

A1rPun
  • 16,287
  • 7
  • 57
  • 90
  • Thanks Pebbl, i have chosen the php solution and changed a little and this really works great for me. Thank you very much for your help. And if i can reward you let me know how i can do this. No i don't send you money :-) – Sietsko Bos Apr 30 '15 at 12:35
  • @SietskoBos You commented on the wrong answer I guess :) – A1rPun Apr 30 '15 at 12:53