Search code examples
phpjqueryhtmlajaxonline-store

Refreshing page on checkbox click without submit button


I am creating online shopping website. And I am new to Ajax and jQuery. The question is: i have selection of colors for t-shirts: 1. Red 2. Blue 3. Green.

I want to load the colored t-shirts image from database (i have stored by image URL) based on user's selection with out submit button. that is, the page should be refreshed every time user selects/de-selects check-box. Can anybody help regarding this? Any help would be great. thank you. The code I tried is:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "mydb";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    // options
    $options = array(
        'Blue' => 'Blue', 
        'red' => 'red', 
        'Green' => 'Green', 
        );

    // sql where
    $sql_where = array('1');
    foreach ($options as $option)
    {
        if (isset($_POST[$option])) $sql_where[] = "field = '$option'";
    }


    // query data
    $res = mysqli_query($conn,"SELECT * FROM try WHERE " . implode(' AND ', $sql_where));


    // html
    $sql_where = array('1');
    foreach ($options as $name => $option)
    {
        ?>
            <input type="checkbox" name="<?= $option?>" id="<?= $option?>" value="1" />
            <label for="<?= $option?>"><?= $name?></label>
        <?php
    }
    echo mysqli_num_rows($res);

    ?>

the code does not refreshes itself everytime I click on checkbox.


Solution

  • Something like this will get you on the right lines...

    $("#check").click(function(){
        $(".myform").submit();
    });
    

    assuming you set class of the checkbox to class="check" and within the form tag you set id="myform"

    The effect of this would be to submit the form just as if you had pressed a submit button, any time the checkbox is clicked.