0

I am struggling with the following PHP and JavaScript codes to have 2 sets of check-boxes filtering a range of data obtained from a MySQL database.

Here is the code:

<script type="text/javascript">
//http://jsbin.com/ujuse/1/edit
$(function() {
    $("input[type='checkbox']").on('change', function() {
        var boxes = [];
        // You could save a little time and space by doing this:
        var name = this.name;
        // critical change on next line
        $("input[type='checkbox'][name='"+this.name+"']:checked").each(function() {
            boxes.push(this.value);
        });
        if (boxes.length) {
            $(".loadingItems").fadeIn(300);
            // Change the name here as well
            $(".indexMain").load('indexMain.php?'+this.name+'=' + boxes.join("+"),
            function() {
                $(".indexMain").fadeIn('slow');
                $(".loadingItems").fadeOut(300);
            });

        } else {
            $(".loadingItems").fadeIn(300);
            $(".indexMain").load('indexMain.php', function() {
                $(".indexMain").fadeIn('slow');
                $(".loadingItems").fadeOut(300);
            });
        }
    });
});
</script>


<?php
function echoCheckboxSet($header, $divClass, $columnName, $setName) {

    include ("connection.php");
$checkboxes = $con -> prepare("SELECT DISTINCT $columnName FROM item_descr ORDER BY $columnName ASC");
$checkboxes->execute();
?>
<div class="bgFilterTitles">
    <h1 class="filterTitles"><?php echo $header;?></h1>
</div>
<div class="<?php echo $divClass; ?>">
<?php
    while ($box = $checkboxes->fetch(PDO::FETCH_ASSOC)):
    $boxColumnName = str_replace('_',' ',$box[$columnName]);
?>
        <input type='checkbox' class='regularCheckbox' name='<?php echo $setName; ?>' value='<?php echo $box[$columnName]; ?>' />
        <font class='similarItemsText'><?php echo $boxColumnName; ?></font>
        <br />
<?php
endwhile;
?>
</div>
<?php
} // end of echoCheckboxSet

// Call our method twice, once for colors and once for prices
echoCheckBoxSet("COLOR", "colors", "color_base1", "color[]");
echoCheckBoxSet("PRICE", "prices", "price", "price[]");
?>

Then I am perfectly getting my check-boxes but when clicking on any of them they don't do anything.

My indexMain.php retrieves the values like this:

$colors = $_GET['color[]'];
echo "TEST".$colors[1];
            $colors = explode(' ', $colors);
            $parameters = join(', ', array_fill(0, count($colors), '?'));
            $items = $con -> prepare("SELECT * FROM item_descr WHERE color_base1 IN ({$parameters})");
            $items ->execute($colors);
            $count = $items -> rowCount();

----------------- Adding the echo:

echo "<div>Showing ".$count."items</div>";
while($info = $items->fetch(PDO::FETCH_ASSOC)) 
{
echo "<div name='item' id='".$info['color_base1']."' class='itemBox'><div class='showItem'><a href='items_descr.php?itemId=".$info[id_item]."'><img class='itemImage' alt='' src='images/$info[imageMid].jpg'></img></div><br />";
echo "<div class='indexItemText'><font class='similarItemsText'><a href='items_descr.php?itemId=".$info[id_item]."'>".$info[name]."</a><font class='price'> - $".$info[price]."</div></div>";
$row_count++;
if ($row_count % 2 == 0) 
    {
echo "<br />"; // close the row if we're on an even record
    }

}

Any idea of what could be going on?

5
  • What do you want to have in output of your page? Commented Dec 26, 2012 at 13:56
  • 3
    Try to do a print_r($_GET) PHP does auto format on inputs[] transforming them into array. You also should use include_once(), you're including the connection params each time you call this function. Commented Dec 26, 2012 at 13:59
  • When doing the print_r after checking 2 of the boxes (Brown and Grey), I get: Array ( [color] => Array ( [0] => Brown Grey ) ) Commented Dec 26, 2012 at 14:38
  • 2
    Then you need to replace $colors = $_GET['color[]']; with $colors = $_GET['color']; Commented Dec 26, 2012 at 14:50
  • please don't forget the jquery tag, so I can filter out this kind of questions before hand. Thank you. Commented Dec 26, 2012 at 15:01

1 Answer 1

2

The problem is when you build the query in your JS function:

'indexMain.php?'+this.name+'=' + boxes.join("+")

This sends color[]=Brown+Grey instead of color[]=Brown&amp;color[]=Grey. A correct (but dirty) way to this is:

'indexMain.php?'+this.name+'=' + boxes.join('&amp;' + this.name + '=')

You could try to use jQuery.param() ( http://api.jquery.com/jQuery.param/ ) to get a nicer code.

Also, in PHP, the checkbox values are available in the array $_GET['color'] (not $_GET['color[]']).

Edit: Sorry, read too quickly.

Answer: As you expect everywhere to use strings, use color instead of color[] in your JS and PHP code.

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

7 Comments

Thanks, I changed the $_GET and now I see the values are received ok, but I still cannot get my items shown. Every time I click a value in the 1st set of checkboxes (a color) the screen is reloaded with no items at all.
When you say screen, do you mean all the page, or your container .indexMain ?
I mean my container. It is reloaded as expected but it does not show any item (even if I am expecting all items of color Brown or Grey...)
Could you put the complete code of indexMain.php ? I don't see anything echoed, except for echo "TEST".$colors[1]; (btw, this should output something like TEST plus the second letter of $colors, as $colors is a string at this line)
Just edited with the echo. Regarding the TEST.$colors[1], it just posts TEST. Nothing else... :(
|

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.