-4

If checkbox is checked I want to store a value in php variable and for unchecked store another value

        <script>
        $('input[type="checkbox"][name="change"]').change(function() {
                if(this.checked) {
                    <?php $sql="SELECT * FROM `order` ORDER BY sl_no ASC"?>
                } else {
                    <?php $sql="SELECT * FROM `order` ORDER BY sl_no DESC"?>
                }
            });
        </script>

        <input type="checkbox" name="change">
Sourabh23
  • 1
  • 2
  • 6
  • 4
    You are mixing Javascript and PHP. Please keep in mind that JS is client-side and PHP is server-side. You have to send an ajax request to your PHP script when calling `change` event handler in your Javascript part. – mario.van.zadel Oct 22 '15 at 05:53
  • See [When and where does JavaScript run, how about PHP? Can I combine the two?](http://stackoverflow.com/q/25093905) – Madara's Ghost Oct 22 '15 at 08:44

1 Answers1

2

You cant mix PHP with JavaScript. To send something back to the server, you have to use a form or ajax. Since ajax isn't a little bit harder to learn, and I dont know how much you already know, you should use forms

<form method="POST">
    <input type="checkbox" name="change">
    <input type="submit" />
    <?php
        if (isset($_POST['change'])) {
            echo "checkbox checked";
        }
    ?>
</form>

To do this with ajax, you have to define an ajax handler script with some logic

<?php
    if (isset($_POST['checked']) && $_POST['checked'] == '1') {
        echo 'checked';
    } else {
        echo 'not checked';
    }
?>

and add some more client side code(using jQuery)

    <script>
    $('input[type="checkbox"][name="change"]').change(function() {
            $.post('ajax.php',
                { checked: this.checked ? '1' : '0' },
                function(data) {
                    $('.result').html(data);
                });
        });
    </script>
Philipp
  • 15,377
  • 4
  • 35
  • 52