views:

273

answers:

1

I want to send an Array with image paths and captions to a PHP script after I sorted the images. I can do 'serialize' or 'toArray' on the lists, but how to get the attributes from the img tag?

<ul class="gallery">
    <li id="li-1">
        <img src="tn/001.jpg" alt="first caption" />
    </li>
    <li mycaption="some caption" id="li-2">
        <img src="tn/002.jpg" alt="second caption with éèçà international chars" />
    </li>
</ul>

$(".gallery").sortable({
    update : function() {
        serial = $('.gallery').sortable('serialize');
        alert(serial);
        /* $.ajax({
            url: "sort.php",
            type: "post",
            data: serial,
            error: function() {alert("theres an error with AJAX");}
        }); */
    }
});
A: 

So here's how I would serialize this, into an object with two members, src_arr and caption_arr:

var getPaths = function() {
    var imgPaths = { 'src_arr': [], 'caption_arr': []};
    $('.gallery img').each(function(){
        imgPaths.src_arr.push($(this).attr('src'));
        imgPaths.caption_arr.push($(this).attr('alt'));
    });
    return imgPaths;
};

So I'd do this with your code:

$.ajax({
    url: "sort.php",
    type: "POST",
    dataType: 'html',
    data: getPaths(),
    success: function(data, textStatus, XMLHttpRequest) {
        // you need to do something in here
        $('#debug').html('<pre>' + data + '</pre>');
    },
    error: function() {
        alert("theres an error with AJAX");
    }
});

The raw data as print_r() out of sort.php looks like:

Array
(
    [src] => Array
        (
            [0] => tn/001.jpg
            [1] => tn/002.jpg
        )

    [caption] => Array
        (
            [0] => first caption
            [1] => second caption with éèçà international chars
        )

)
artlung
Thanks so much! So there is no need to use serialize? I was thinking the same thing last night. It could be usefull if you are sending just some ID's fro db update maybe?
FFish
artlung