Posting multiple variable in URL and working with checkboxes

谁说胖子不能爱 提交于 2020-01-17 11:06:39

问题


This is based on the following example:

http://www.w3schools.com/php/php_ajax_database.asp

The differences are mainly that I am using checkboxes instead of select and where I would want to be able to select multiple items across multiple checkboxes forms:

Below are the two problems I have:

  1. I want to be able to post multiple variable in the URL because as of now only one variable can be posted, and I get an error for the one not selected.
  2. I want to be able to select multiple checkboxes at once. At its current state you can select multiple checkboxes but the results is only adjusted on the last checkboxes. FOr instance if checkbox 2 + 3 is check only 3 will be displayed, when I would want the result of 2 and 3.

Below is the html portion:

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script>
            function showUser() {
                var selectedPerson = $('#testform').serialize();
                                                    document.getElementById("txtHint").innerHTML = "<div class='loading-indication'><img src='ajax-loader.gif' /> &nbsp; Please wait... Loading New Courses...</div>";


                $.ajax({
                    url:'getuser.php',
                    type:'post',
                    data:selectedPerson,
                    success:function(res){
                        $('#txtHint').html(res);
                    }
                })
            }
        </script>

        <script>
            function showUser2() {
                var selectedPerson = $('#testform2').serialize();
                                                    document.getElementById("txtHint").innerHTML = "<div class='loading-indication'><img src='ajax-loader.gif' /> &nbsp; Please wait... Loading New Courses...</div>";


                $.ajax({
                    url:'getuser.php',
                    type:'post',
                    data:selectedPerson,
                    success:function(res){
                        $('#txtHint').html(res);
                    }
                })
            }
        </script>
    </head>
    <body>

        <form id="testform">
            <input onchange="showUser();" name="person[]" type="checkbox" value="1">One<br>
            <input onchange="showUser();" name="person[]" type="checkbox" value="2">Two<br>
            <input onchange="showUser();" name="person[]" type="checkbox" value="3">Three<br>
            <input onchange="showUser();" name="person[]" type="checkbox" value="4">Four<br>
            <input onchange="showUser();" name="person[]" type="checkbox" value="5">Five<br>
        </form>

        <form id="testform2">
            <input onchange="showUser2();" name="person2[]" type="checkbox" value="communication">communication<br>
            <input onchange="showUser2();" name="person2[]" type="checkbox" value="business">business<br>
            <input onchange="showUser2();" name="person2[]" type="checkbox" value="html and css">Three<br>
            <input onchange="showUser2();" name="person2[]" type="checkbox" value="sql">Four<br>
            <input onchange="showUser2();" name="person2[]" type="checkbox" value="windows">Five<br>
                      <input onchange="showUser2();" name="person2[]" type="checkbox" value="cloud">Cloud<br>
            <input onchange="showUser2();" name="person2[]" type="checkbox" value="microsoft office">Java<br>

        </form>

        <br>
        <div id="txtHint"><b>Person info will be listed here...</b></div>

    </body>
</html>

Below is the PHP part:

<!DOCTYPE html>
<html>
<head>
<style>
table {
    width: 100%;
    border-collapse: collapse;
}

table, td, th {
    border: 1px solid black;
    padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
 $person = '';
        $person  = isset($_POST['person']) ? $_POST['person'] : '';
        $allIds = '';
        if($person!=''){
            foreach($person as $personid){
                $allIds .= $personid.',';
            }
            $personid = rtrim($allIds,',');
        }


 $person2 = '';
        $person2  = isset($_POST['person2']) ? $_POST['person2'] : '';
        $allIds = '';
        if($person2!=''){
            foreach($person2 as $personid2){
                $allIds .= $personid2.',';
            }
            $personid2 = rtrim($allIds,',');
        }


include("includes/db.php"); 



global $con;


$sql= "SELECT * FROM courses WHERE (course_duration IN ('" . $personid . "')) OR (course_duration IN ('" . $personid2. "')) LIMIT 10";
$result = mysqli_query($con,$sql);
$sqlCount = "SELECT * FROM courses WHERE (course_duration IN ('" . $personid . "')) OR (course_subc1 IN ('" . $personid2. "')) OR (course_subc3 IN ('" . $personid2. "')) OR (course_subc1 IN ('" . $personid2. "')) OR (course_subc4 IN ('" . $personid2. "')) OR (course_subc5 IN ('" . $personid2. "'))";
$get_crs_count = mysqli_query($con, $sqlCount);
$count_rows = mysqli_num_rows($get_crs_count);
echo '<p style="margin-bottom: 8px;margin-top: 8px;font-size:18px;"><b>Number of courses available: </b>' . $count_rows ;
while($row_crs = mysqli_fetch_array($result)){ 

    $crs_id = $row_crs['course_id'];
        $crs_cat = $row_crs['course_cat'];

    $crs_provider = $row_crs['course_provider'];

    $crs_title = $row_crs['course_title'];
        $crs_price = $row_crs['course_price'];
          $crs_city= $row_crs['course_city'];
                      $crs_category= $row_crs['course_cat1'];

          $crs_date= $row_crs['course_date1'];


$crs_sdesc= $row_crs['course_sdesc'];
$crs_shortdesc = mb_strimwidth("$crs_sdesc",0,140,"...");
        $crs_image = $row_crs['course_image'];
        $provider_image = $row_crs['provider_image'];


  echo " <article class='search-result row'><center>
      <div class='col-xs-12 col-sm-12 col-md-3' id='thumbnailContainer'>
        <a href='#' title='Lorem ipsum' class='thumbnail' id='resultThumbnail'><img src='$provider_image' /></a>
     <a href='searchPage.php?crs_price=$crs_price' style='color:black;'>  <button id='resultprice'><span id='resultpriceText'>$ $crs_price</span></button></a>
      </div>
      <div class='col-xs-12 col-sm-12 col-md-2'>
        <ul class='meta-search' id='listDesign'>
        <a href='searchPage.php?crs_date=$crs_date' style='color:white;'>   <li><button id='resultInfo'><i class='fa fa-calendar fa-1x'><span id='iconText'>  $crs_date</span></i></button></li></a>
         <a href='searchPage.php?crs_category=$crs_category' style='color:white;'>   <li><button id='resultInfo2'><i class='fa fa fa-tags fa-1x'><span id='iconText'> $crs_category</span></i></button></li></a>
<a href='searchPage.php?crs_provider=$crs_provider' style='color:white;'><li><button id='resultInfo'><i class='fa fa-graduation-cap fa-1x'><span id='iconText'>  $crs_provider</span></i></button></li></a>
<a href='searchPage.php?city=$crs_city' style='color:white;'><li><button id='resultInfo'><i class='fa fa-map-marker fa-1x'><span id='iconText'> $crs_city</span></i></button></li></a>
        </ul>
      </div></center>
      <div class='col-xs-12 col-sm-12 col-md-7 excerpet'>
        <h3 id='resultHeading'><a href='coursePage.php?crs_id=$crs_id' id='headingLinking'><b>$crs_title</b></a></h3>

        <div id='courseshortDescription'>
$crs_shortdesc
 <center><a href='coursePage.php?crs_id=$crs_id' style='color:white;'><button class='btn btn-danger' id='findoutBtn'>Find Out More</button></a> </center>
        </div>  

</div>

      <span class='clearfix borda'></span>
    </article>";
}

mysqli_close($con);
?>
</body>
</html>

Update:

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script>
            function showUser() {
var selectedPeople = {person: []};
$('input[name="person"]:checked').each(function() {
    selectedPeople.person.push($(this).val());
});                                                    document.getElementById("txtHint").innerHTML = "<div class='loading-indication'><img src='ajax-loader.gif' /> &nbsp; Please wait... Loading New Courses...</div>";


                $.ajax({
                    url:'getuser.php',
                    type:'post',
                    data:selectedPerson,
                    success:function(res){
                        $('#txtHint').html(res);
                    }
                })
            }
        </script>

        <script>
            function showUser2() {
var selectedPeople = {person2: []};
$('input[name="person2"]:checked').each(function() {
    selectedPeople.person2.push($(this).val());
});                                                    document.getElementById("txtHint").innerHTML = "<div class='loading-indication'><img src='ajax-loader.gif' /> &nbsp; Please wait... Loading New Courses...</div>";


                $.ajax({
                    url:'getuser.php',
                    type:'post',
                    data:selectedPerson,
                    success:function(res){
                        $('#txtHint').html(res);
                    }
                })
            }
        </script>
    </head>
    <body>

        <form id="testform">
            <input onchange="showUser();" name="person[]" type="checkbox" value="1">One<br>
            <input onchange="showUser();" name="person[]" type="checkbox" value="2">Two<br>
            <input onchange="showUser();" name="person[]" type="checkbox" value="3">Three<br>
            <input onchange="showUser();" name="person[]" type="checkbox" value="4">Four<br>
            <input onchange="showUser();" name="person[]" type="checkbox" value="5">Five<br>
        </form>

        <form id="testform2">
            <input onchange="showUser2();" name="person2[]" type="checkbox" value="communication">communication<br>
            <input onchange="showUser2();" name="person2[]" type="checkbox" value="business">business<br>
            <input onchange="showUser2();" name="person2[]" type="checkbox" value="html and css">Three<br>
            <input onchange="showUser2();" name="person2[]" type="checkbox" value="sql">Four<br>
            <input onchange="showUser2();" name="person2[]" type="checkbox" value="windows">Five<br>
                      <input onchange="showUser2();" name="person2[]" type="checkbox" value="cloud">Cloud<br>
            <input onchange="showUser2();" name="person2[]" type="checkbox" value="microsoft office">Java<br>

        </form>

        <br>
        <div id="txtHint"><b>Person info will be listed here...</b></div>

    </body>
</html>

the php file

<!DOCTYPE html>
<html>
<head>
<style>
table {
    width: 100%;
    border-collapse: collapse;
}

table, td, th {
    border: 1px solid black;
    padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$person = filter_input(INPUT_POST, 'person', FILTER_VALIDATE_INT, FILTER_FORCE_ARRAY);
foreach ($person as $personid)
{
    $allIds .= $personid.',';
}
$personid = rtrim($allIds,',');
       }


$person2 = filter_input(INPUT_POST, 'person2', FILTER_VALIDATE_INT, FILTER_FORCE_ARRAY);
foreach ($person2 as $personid2)
{
    $allIds2 .= $personid2.',';
}
$personid2 = rtrim($allIds2,',');
       }


include("includes/db.php"); 



global $con;


$sql= "SELECT * FROM courses WHERE (course_duration IN ('" . $personid . "')) OR (course_duration IN ('" . $personid2. "')) LIMIT 10";
$result = mysqli_query($con,$sql);
$sqlCount = "SELECT * FROM courses WHERE (course_duration IN ('" . $personid . "')) OR (course_subc1 IN ('" . $personid2. "')) OR (course_subc3 IN ('" . $personid2. "')) OR (course_subc1 IN ('" . $personid2. "')) OR (course_subc4 IN ('" . $personid2. "')) OR (course_subc5 IN ('" . $personid2. "'))";
$get_crs_count = mysqli_query($con, $sqlCount);
$count_rows = mysqli_num_rows($get_crs_count);
echo '<p style="margin-bottom: 8px;margin-top: 8px;font-size:18px;"><b>Number of courses available: </b>' . $count_rows ;
while($row_crs = mysqli_fetch_array($result)){ 

    $crs_id = $row_crs['course_id'];
        $crs_cat = $row_crs['course_cat'];

    $crs_provider = $row_crs['course_provider'];

    $crs_title = $row_crs['course_title'];
        $crs_price = $row_crs['course_price'];
          $crs_city= $row_crs['course_city'];
                      $crs_category= $row_crs['course_cat1'];

          $crs_date= $row_crs['course_date1'];


$crs_sdesc= $row_crs['course_sdesc'];
$crs_shortdesc = mb_strimwidth("$crs_sdesc",0,140,"...");
        $crs_image = $row_crs['course_image'];
        $provider_image = $row_crs['provider_image'];


  echo " <article class='search-result row'><center>
      <div class='col-xs-12 col-sm-12 col-md-3' id='thumbnailContainer'>
        <a href='#' title='Lorem ipsum' class='thumbnail' id='resultThumbnail'><img src='$provider_image' /></a>
     <a href='searchPage.php?crs_price=$crs_price' style='color:black;'>  <button id='resultprice'><span id='resultpriceText'>$ $crs_price</span></button></a>
      </div>
      <div class='col-xs-12 col-sm-12 col-md-2'>
        <ul class='meta-search' id='listDesign'>
        <a href='searchPage.php?crs_date=$crs_date' style='color:white;'>   <li><button id='resultInfo'><i class='fa fa-calendar fa-1x'><span id='iconText'>  $crs_date</span></i></button></li></a>
         <a href='searchPage.php?crs_category=$crs_category' style='color:white;'>   <li><button id='resultInfo2'><i class='fa fa fa-tags fa-1x'><span id='iconText'> $crs_category</span></i></button></li></a>
<a href='searchPage.php?crs_provider=$crs_provider' style='color:white;'><li><button id='resultInfo'><i class='fa fa-graduation-cap fa-1x'><span id='iconText'>  $crs_provider</span></i></button></li></a>
<a href='searchPage.php?city=$crs_city' style='color:white;'><li><button id='resultInfo'><i class='fa fa-map-marker fa-1x'><span id='iconText'> $crs_city</span></i></button></li></a>
        </ul>
      </div></center>
      <div class='col-xs-12 col-sm-12 col-md-7 excerpet'>
        <h3 id='resultHeading'><a href='coursePage.php?crs_id=$crs_id' id='headingLinking'><b>$crs_title</b></a></h3>

        <div id='courseshortDescription'>
$crs_shortdesc
 <center><a href='coursePage.php?crs_id=$crs_id' style='color:white;'><button class='btn btn-danger' id='findoutBtn'>Find Out More</button></a> </center>
        </div>  

</div>

      <span class='clearfix borda'></span>
    </article>";
}

mysqli_close($con);
?>
</body>
</html>

no errors are shown but what happens when a checkbox is selected, it just stops at this line (found on index js):

});                                                    document.getElementById("txtHint").innerHTML = "<div class='loading-indication'><img src='ajax-loader.gif' /> &nbsp; Please wait... Loading New Courses...</div>";

回答1:


Instead of var selectedPerson = $('#testform').serialize(); try this:

var selectedPeople = {person: []};
$('input[name="person[]"]:checked').each(function() {
    selectedPeople.person.push($(this).val());
});

and in your PHP change $person = ... to:

$person = filter_input(INPUT_POST, 'person', FILTER_VALIDATE_INT, FILTER_FORCE_ARRAY);
foreach ($person as $personid)
{
    $allIds .= $personid.',';
}
$personid = rtrim($allIds,',');


来源:https://stackoverflow.com/questions/29237960/posting-multiple-variable-in-url-and-working-with-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!