rgdigi
rgdigi

Reputation: 1747

Pass element IDs into an array for POST form process

So say I've got a series of images created with a php loop ->

<img src="http://..._1.jpg" class="profile-thumb" id="12345678">
<img src="http://..._2.jpg" class="profile-thumb" id="12345677">
<img src="http://..._3.jpg" class="profile-thumb" id="12345676">

The user can select the image elements by clicking on them jquery style a la ->

    $(".profile-thumb").click(function () {
        if ($(this).hasClass("active")) {
            $(this).removeClass('active');
        } else {
            $(this).addClass('active');
        }
    });

So that when you click an image it adds an '.active' class to the image element ->

<img src="http://..._3.jpg" class="profile-thumb active" id="12345676">

How would I pass all the selected elements IDs into an array for use in a form process with PHP?

User journey:

Click photo -> Adds ID to array -> Click a submit button -> Uses POST array to perform a function with all IDs (e.g. send an email to all users using the IDs identified as active)


I want to pass the array to a loop with an AJAX call and echo output to the #post-info div ->

    $.get('post.php', function(data) {
        $('#post-info').html(data);
    });

How will I then read the POST array with a foreach loop?


Solution:

HTML:

<button id="share" class="off">
    <span>Sharer</span>
</button>
<div id="sharer">
<!-- Array will echo here -->
</div>

Javascript:

    $("#share").click(function () {
        //Create var array
        var list = $('.active-profile').map(function(){return this.id;}).toArray();

        $.post('sharer.php', {ids:list}, function(data) {
            $('#sharer').html(data);
        });

    });

PHP (sharer.php)

        foreach ($_POST['ids'] as $id) {
            echo 'ID: ';
            echo $id;
        }

The javascript array (list) is sent via jquery POST and echo'd in the #sharer div

Upvotes: 2

Views: 2732

Answers (2)

dm03514
dm03514

Reputation: 55972

To sent an array of values to php you need to use a slightly different syntax. For each id you can create a url that looks something like.

http://test.com/?img_id[]=1&img_id[]=2&img_id[]=3

This will let you get the value img_id as an array in php.

$_POST['img_id'] // array of values. 
foreach ($_POST['img_id'] as $id) {
  print $id;
}  
// 1
// 2
// 3

Upvotes: 0

Rob W
Rob W

Reputation: 349142

$('.profile-thumb.active').map(function(){return this.id}).toArray();

Also, instead of if-hasClass-removeClass-else-addClass, you can simply use:

$(".profile-thumb").click(function () {
    $(this).toggleClass("active");
});

Demo: http://jsfiddle.net/ErVbS/

Upvotes: 3

Related Questions