-3

I have use the following code

order.php

        <script type="text/javascript">
        function processForm() { 
        $.ajax( {
            type: 'POST',
            url: 'ajax.php',
            data: { checked_box : $('input:checkbox:checked').val()},

            success: function(data) {
                $('#results').html(data);
            }
        } );
        }
        </script>

        <input type="checkbox" name="checked_box" value="1" onclick="processForm()">

And ajax.php

<?php
include "config.php";
$checkbox = intval($_POST['checked_box']);
echo $checkbox;
if($checkbox == 1){
    $Query="SELECT * FROM `order` ORDER BY sl_no DESC";
}else{
    $Query="SELECT * FROM `order` ORDER BY sl_no ASC";    
}
$result=mysql_query($Query);
echo $Query;
while($row = mysql_fetch_object($result)) { 
?>

It works good but when I unchecked then error showing

Notice: Undefined index: checked_box in C:\xampp\htdocs\website\admin\ajax.php on line 24

How to avoid this error???

Sourabh23
  • 1
  • 2
  • 6

4 Answers4

0

It is not an error, but a notice. You will get that kind of notices if you try to access non initialized variables. Just initialize it with the appropiate start value.

The tricky part in your code is that you assume you'll get the value of the checkbox because it is included in the form. But it happens that the checkbox are not sent UNLESS THEY HAVE BEEN CHECKED.

Amarnasan
  • 14,939
  • 5
  • 33
  • 37
0

Instead of intval($_POST['checked_box']); use isset($_POST['checked_box']); to make sure the value exists at all.

After that you can use intval if you still need that value.

Sean DuBois
  • 3,972
  • 1
  • 11
  • 22
0

It's all because only checked checkboxes are included in POST request. So you need to check if your checked_box key exists to figure out checkbox was set or not:

if(isset($_POST['checked_box']) {
   .. set
} else {
   .. not set
}
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
0

I have a select dropdown box

<select name="status" id="status" onchange="changeStatus()">
    <option value="step_1">step_1</option>
    <option value="step_2">step_2</option>
    <option value="step_3">step_3</option>
    <option value="step_4">step_4</option>
</select>

And my javascript

    <script>
        function changeStatus() {
            $('select.changeStatus').change(function(){
                $.ajax({
                        type: 'POST',
                        url: 'update_status.php',
                        data: {changeStatus: $('select.changeStatus').val()},
                        dataType: 'html'
                 });
            });
        });
    </script>

So I want the value selected from the select dropdown box send to the php file(update_status.php)

Sourabh23
  • 1
  • 2
  • 6