Home > html, jQuery, php > Passing array of checkbox values to php through jQuery (example)

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

input.html

<!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>

process.php

<?php
        print_r(@$_POST['list']);

Test-run screenshot:

Live demo (Using google app engine therefore output is slightly different to the screenshot above. The relevant code that deals with the post request is as follow:

class Chkbox(webapp.RequestHandler):
    def get(self):
        ...

    def post(self):
        d=self.request.get_all( 'list[]' )
        self.response.out.write(d)

)

Advertisements
Categories: html, jQuery, php
  1. October 21, 2011 at 5:13 pm

    Thanks for sharing this usefull code.

    • ricoch3n
      October 22, 2011 at 12:07 am

      You are welcome. Glad it helps.

  2. December 14, 2011 at 8:19 am

    hello,

    I was looking for something like this but I prefer to display the result in a container and the results to be changed as the user click the checkboxes no when he click on submit button I have done this so far and I need some help on how I coul change the select query that I have in the sresults.php

    html code

    GREECE
    USA
    ITALY
    SPAIN

    $(‘#sidebar > input:checkbox’).change (
    function ()
    {
    reloadInfo ();
    });

    function reloadInfo ()
    {
    var cbdata = new Array();
    $(‘#sidebar > input:checkbox’).each (
    function ()
    {
    cbdata[$(this).val()] = $(this).is(‘:checked’);
    });
    //Set reload image while waiting for ajax
    $(‘#container’).html(”);
    $.ajax({
    url: “sresults.php”,
    type: “POST”,
    data: (cbdata),
    dataType: “html”,
    async:false,
    success: function(msg){
    $(‘#container’).html(msg);
    },

    statusCode: {
    404: function() {
    $(‘#container’).html(‘Error loading’);
    }
    }
    });
    }

    the sresults.php

    $result = mysql_query(“SELECT id, name, cat FROM mytable”);

    while ($row = mysql_fetch_array($result)) {
    echo ‘‘.$row{‘name’}.’
    ‘;
    }

    ?>
    Can you please help me
    How can I pass the values to my $result query? I found some examples like serialize or $_POST methos but I didn’t manage to make work right

    thank you

    • ricoch3n
      December 16, 2011 at 6:26 am

      Hi,
      If I understand you correctly, you were trying to pass the selected checkboxes array to the sresults.php script on the server. All you need to do is to
      1. On the client side’s html code, give each country item an unique rel attribute, which stores the
      2. On the client side’s javascript code, push the rel attribute of each selected item into your cbdata array and change the following code

      $.ajax({
          url: “sresults.php”,
          type: “POST”,
          data: (cbdata),
          dataType: “html”,
      ...
      

      into, for example

      $.ajax({
          url: “sresults.php”,
          type: “POST”,
          data: {countries:cbdata},
          dataType: “html”,
      ...
      

      3. On the server side
      You’ll need to use the submitted data $_POST[‘countries’] in your mysql statement.

              $countries=$_POST['countries'];
              // you mysql connection codes
              foreach($countries as &$country) {
                      $country=sprintf("country='%s'", mysql_real_escape_string($country));
              }
              $where=join(' or ', $countries);
              $query="select ... where $where";
              ...
      
      

      mysql_real_escape_string is used to escape each checked value because it’s never a good idea to pass user inputs directly to mysql. Hope that helps.

  3. February 9, 2013 at 1:46 pm

    Not getting Selected checkbox in response……

    • February 9, 2013 at 8:02 pm

      Any example html/js codes I can take a look? It’s really hard to guess what might go wrong without the codes. Also how did you do the tests? Have you used any developer tools that come with the browser to troubleshoot the problem?

  4. January 7, 2016 at 8:16 am

    Excelent, did not find a way to pass the values til now, thanks for sharing!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: