Thursday 10 October 2013

Passing array of checkbox values to php through jQuery (example)


<!DOCTYPE html>
<html>
<head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript">
                function doit() {
                        var p=[];
                        $('input.cb').each( function() {
                                if($(this).attr('checked')) {
                                        p.push($(this).attr('rel'));
                                }
                        } );
                        $.ajax( {
                                url:'/process.php',
                                type:'POST',
                                data: {list:p},
                                success: function(res) {
                                        alert(res);
                                }
                        });
                }
        </script>
</head>
<body>
        <input type="checkbox" class="cb" rel="1"></input>This is 1<br />
        <input type="checkbox" class="cb" rel="abc"></input>This is abc<br />
        <input type="checkbox" class="cb" rel="999"></input>This is 999<br />
        <a href="javascript:void(0)" onclick="doit()">Click</a>
</body>
</html>

print_r(@$_POST['list']);