Send a MySQL query when pressing checkbox with AJAX

时间:2016-10-15 17:04:41

标签: javascript php jquery mysql ajax

I am trying to send an update query when a checkbox is pressed, using AJAX. How can I do this?

HTML imports:

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="js/checkbox.js"></script>

HTML checkbox:

<td>
    <input type="checkbox" name="vehicle" value="" class="checkbox">  Ingevoerd<br>
</td>

(Yes my checkbox is in a table, I don't know if this has to be in a form.)

JavaScript code:

$(".checkbox").change(function() {
    window.alert(5 + 6);
    $.ajax({
        url: '../ingevoerd.php'
    });
});

(the window.alert is not triggered when I press the checkbox)

PHP code:

$stmt = $db->prepare('UPDATE table SET temp=0 where id = 1');
$stmt->execute();
var_dump('test');

1 个答案:

答案 0 :(得分:2)

I guess your javascript code runs before your html exists, so when your browser is trying to find $(".checkbox"), there aren't any elements with the checkbox class yet.

You should have the code running only after the document is ready:

$(function() {
    $(".checkbox").change(function() {
        window.alert(5 + 6);
        $.ajax({
            url: '../ingevoerd.php'
        });
    });
});

In the next example you can see that nothing will happen (because the javascript code exists before the elements are available in the DOM):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  $('#d1').css('background', 'red');
</script>
<div id="d1">some block</div>

Same example, but wait for the DOM to be ready (this example will work as expected):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  $(function() {
    $('#d1').css('background', 'red');
  });
</script>
<div id="d1">some block</div>