2

I am trying to update a value in DB while checking checkbox (1 or 0) with jquerys $.post or $.ajax. I would really appreciate some help. Here is my code:

HTML

<div class="onoffswitch">
     <?php
    $yesno = (bool)$baner['noti'];
    $checked = ($yesno) ? 'checked="checked"' : '';  
     ?>
   <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" value="1" id="myonoffswitch" <?php echo $checked; ?>>
   <label class="onoffswitch-label" for="myonoffswitch"></label>
</div>

jQuery

$(function(){
    $("#myonoffswitch").click(function(){
        $.post("notification.php");
        })
    });

notification.php

connections stuffs...

$yesno = ( isset($_POST['onoffswitch']) ) ? 1 : 0;
$sql = "UPDATE baner SET noti='$yesno'";
1
  • 1
    What seems to go wrong? It doesn't appear that you're sending any data with your post request. You might find the documentation for post() helpful, especially the examples. Commented Mar 21, 2016 at 19:46

2 Answers 2

3

You almost have it. you just need to read your checkbox state and send it back with your POST request.

$(function(){
    $("#myonoffswitch").click(function(){
        var isOn = $("#myonoffswitch").prop("checked");
        $.post("notification.php", { 'onoffswitch': isOn }, function (result) {
            //handle success here
        });
    });
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your replay. I am getting error on this line: var isOn $("#myonoffswitch").prop("checked");
I think there is missing an equal sign. But it wont work for me with or without. Any Idea? When I am changing manually to 0 it change the first time when I click to 1, but It wont go back to 0.
1

Try this with $.ajax. It is used widely for update data without redirect page.

$("#myonoffswitch").click(function(){
    $.ajax({
       var onoffswitch=$('#myonoffswitch').val();
       type: "POST",
       url: "notification.php", //Relative or absolute path to notification.php file
       data: {onoffswitch: onoffswitch},
       success: function(response) {
                content.html(response);
       }
    });  

});

notification.php

connections stuff...

$yesno = ( isset($_POST['onoffswitch']) ) ? 1 : 0;
$sql = "UPDATE baner SET noti='$yesno'";

Comments

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.