Jürgen Paul
Jürgen Paul

Reputation: 15007

Reading serialized jquery data in PHP (multiple checkboxes)

JQUERY:

$(document).ready(function(){
    $('form').submit(function(){
        var content = $(this).serialize();
        //alert(content);
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'http://localhost/test/generate',
            timeout: 15000,
            data:{  content: content },
            success: function(data){
                $('.box').html(data).fadeIn(1000);
            },
            error: function(){
                $('.box').html('error').fadeIn(1000);
            }
        });
        return false;
    });
});

HTML:

<form>
<input type="checkbox" value="first" name="opts[]">
<input type="checkbox" value="second" name="opts[]">
<input type="checkbox" value="third" name="opts[]">
<input type="submit">
</form>

How do i process (or read) multiple checked checkbox's value in PHP? I tried doing $_POST['content'] to grab the serialized data but no luck.

Upvotes: 2

Views: 4757

Answers (4)

Mark Pruce
Mark Pruce

Reputation: 945

The chosen answer still didn't work for me, but here is what did:

var checkedBoxesArr = new Array();
$("input[name='checkedBoxes']:checked").each(function() {
    checkedBoxesArr.push($(this).val());
});
var checkedBoxesStr = checkedBoxesArr.toString(); 
var dataString = $("#" + formID).serialize() + 
                  '&checkedBoxesStr=' + checkedBoxesStr;

[The above code goes in your javascript, before serializing the form data]
First, cycle through the checked boxes and put them into an array.
Next, convert the array to a string.
Last, append them to the serialized form data manually - this way you can reference the string in your PHP alongside the rest of the serialized data.

This answer came partly from this post: Send multiple checkbox data to PHP via jQuery ajax()

Upvotes: 0

jogesh_pi
jogesh_pi

Reputation: 9782

there are an Error in your code :

  1. The url should be url: 'http://localhost/test/generate.php' with the extension name

Upvotes: -2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

Replace:

data:{  content: content } // <!-- you are prefixing with content which is wrong

with:

data: content

Now in your PHP script you can use $_POST['opts'] which normally should return an array.

Upvotes: 5

Grrbrr404
Grrbrr404

Reputation: 1805

Try

echo $_POST['opts'][0]. "<br />";
echo $_POST['opts'][1]. "<br />";
echo $_POST['opts'][2]. "<br />";

You post an array to the Server and it is available in the post variable 'opts'. Remember: Unchecked boxes dont get posted.

Upvotes: 1

Related Questions