3

User has option to select from checkboxes. I want to get the checkbox as an array via jquery, then pass to php thru ajax. It doesnt seem that I am able to get array and process. I've seen other answers on SO, but none seem to work.

HTML/PHP

<?php foreach ( $results['buckets'] as $bucket ) { ?>
    <div><?php echo $bucket->name ?></div>
    <input type="checkbox" name="buckets[]" id="<?php echo strtolower( $bucket->name ) ?>" class="buckets" value="<?php echo $bucket->id ?>" style="visibility: hidden" /><label for="<?php echo strtolower( $bucket->name ) ?>" class="<?php echo strtolower( $bucket->name ) ?>"><?php echo $bucket->name ?></label>
<?php } ?>

JS

$( function() {

    $( "#form" ).submit( function() {

        var buckets = new Array();
        $( "input[name='buckets[]']:checked" ).each( function() {
                buckets.push( $( this ).val() );
        } );
        var valid = false;

        $.ajax( {

            type: "POST",
            url: "/scripts/validateBucketSelect.php",
            data: buckets,
            cache: false,
            async: false,

            success: function( error ) {

                if ( error == "null" ){

                    valid = true;

                } else {

                    $( ".errorMessage" ).html( error );
                }
            }
        } );

        return valid;
    } );
} );

PHP

$postData = $_POST;

if ( count( $postData['buckets'] ) < 3 ) {
    echo "Oops! You have to select at least 3 buckets.";
} elseif ( count( $postData['buckets'] ) > 5 ) {
    echo "Oops! You cannot select more than 5 buckets.";
} else {
    echo "null";
}
1
  • 1
    checked the js to see if buckets is populated? checked the php to see if POST is populated - a little debugging goes a long way Commented Sep 3, 2013 at 1:37

1 Answer 1

2

buckets is an array, but you need the key in the php script.

So data: buckets, should be data: {buckets : buckets}, then you could get with $_POST['buckets'].

If you just use data: buckets,, then the $_POST is already the data you want.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.