jQuery forward array to server

Updated peter_budo 2 Tallied Votes 904 Views Share

In my current project we need to provide drag&drop functionality of items from left to right and vice-versa and on click of the button send array of item IDs to server.
Main problem was that we couldn't get array across to server and online examples that we found did not work.

Above snippet will grab "id" attribute of all list elements (order/unorder list) from container with ID of "sortable2". Push IDs from listed elements to array "ids". After that, it will get currently selected value from drop down menu and store it in "id" variable that is used in next step to postfix URL.

Array submission is done through jQuarey.ajax(). Array of IDs is caste in "data" option of this method as data: ({'listID':ids}) where "listID" represents variable name under which we will retrieve this array on server side.

Addition of "success" option is just icing on the cake ;)

$('#save-button').click(function() {
        var ids = [];
        $('#sortable2 > li.stories').each(function(el) {
            ids.push($(this).attr('id'));
        });

        var id = $('#brsel option:selected').attr('value');
        var url = "$http://www.daniweb.com!Merge.jspa?section="+id;
        jQuery.ajax({type: "POST",
            url: url,
            data: ({'listID':ids}),
            success: function(){
                alert("Changes been succesfully saved");
        }});
    });