Hello everyone
So, my objective is to update four rows in my database (id-> int , status->tinyint) from 0 to 1 and vice verca using a checkbox. This should be done without refreshing the page and using a form without submit button. Based on my research, I was able to write the following code but not sure if it is correct as I am very new to this part. Can someone please help me with this, I have been trying to do this for a very long time.
Thanks you

Index.php

<form id="myform" method="post" action="">
<input type="checkbox" class="ids" name="ids[]" value="1">
<input type="checkbox" class="ids" name="ids[]" value="2">
<input type="checkbox" class="ids" name="ids[]" value="3">
<input type="checkbox" class="ids" name="ids[]" value="4">
</form>

<div id="response"></div>


<script>
 $(document).ready(function() {
     $('#myform').click(function() {

     var state = ($(this).is(':checked')) ? '1' : '0';

       $.ajax({
         url: "test.php",
         type: "post",
         data: $('.ids:checked').serialize(),state: state
         success: function(data) {
         $('#response').html(data);
          }
      });


    });
 });
</script>

test.php

<?php
include_once("db.php");

if (isset($_POST['ids'])) {
$id_value = $_POST['ids'];
 $state = (int)$_POST['state'];

        foreach($id_value as $check) {

          $sql_check = "UPDATE toggle SET status= '$state' WHERE id = '$check' ";
          $result_check = mysqli_query($conn,$sql_check);

         if($result_check){
             echo "sucess";
         }else{
             echo "failure";
         }
        }

}
?>

Recommended Answers

All 9 Replies

What results have you had so far?

commented: Thanks for the relpy. Well I get no errors on the page and nothing in inspector as well. +0

You can use console.log() within the trigger call

$('#myform').click(function() {
    console.log("Click event triggered");

in order to see if the trigger is ran through the console. If you click the "Network" tab in the "Inspect" you can see if the XHR/AJAX request is being sent.

commented: Ok, I am getting the message "Click event triggered", status code "200". So the form is getting submit +0

Yep so what does the response on the "Network" tab say?

You should be able to click the request and it'll open another panel with headers and you want the one which reads "Preview" or "Response".

This is the data that your endpoint returns

commented: Yes so on request I get this value ids[]:[..] 0:"1",1:"2" and for reponse nothing +0

Try var dumping the $_POST object

var_dump($_POST);

If this returns nothing then you know there is an issue with the reference back to the data that was sent

commented: Yes it does return nothing +0

Did you put it outside of this logic?

var_dump($_POST); // Here
if (isset($_POST['ids'])) {
       $id_value = $_POST['ids'];
       $state = (int)$_POST['state'];

        foreach($id_value as $check) {

          $sql_check = "UPDATE toggle SET status= '$state' WHERE id = '$check' ";
          $result_check = mysqli_query($conn,$sql_check);

         if($result_check){
             echo "sucess";
         }else{
             echo "failure";
         }
        }
commented: No sorry my mistake, yeah now it generating array(1) { ["ids"]=> array(1) { [0]=> string(1) "1" } } when I click the first checkbox +0

$state = (int)$_POST['state']; Refers to a post variable that has not been passed

commented: So how do I resolve it? Sorry for asking again I am new to programming +0

I adapted you ajax method to this and it works:

    $.ajax({
        url: "test.php",
        type: "post",
        data: $(this).serialize() + "&state=" + state
    }).done(function(data) {
        $('#response').html(data);
    });
commented: Thank you it is showing success but the database is not getting updated. I think the issue with state: var state = ($(this).is(':checked')) ? '1' : '0 +0

That's becuase the trigger is bound to the FORM element so when you use $(this) a little later on, you're refering to the form and not the checkbox.

The form only send the ID's of checkboxes that have been checked if this helps? Alternatively you need to bind the trigger on the checkbox and use it's state to update a hidden field that can contain the states and then serialized with the form data

commented: Thanks. I kinda understand what you mean. Can you please provide an example or guide on how to do it? +0

Form:

<form id="myform" method="post" action="">
<input type="checkbox" class="ids" name="ids[]" value="1">
<input type="checkbox" class="ids" name="ids[]" value="2">
<input type="checkbox" class="ids" name="ids[]" value="3">
<input type="checkbox" class="ids" name="ids[]" value="4">
</form>

<div id="response"></div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
 $(document).ready(function() {
     $('.ids').click(function() {
        var state = ($(this).is(':checked')) ? '1' : '0';
        var myobj = {}
        console.log($(this).serialize())
        $.ajax({
            url: "test.php",
            type: "post",
            data: $(this).serialize() + "&state=" + state
        }).done(function(data) {
            $('#response').html(data);
        });
    });
 });
</script>

Endpoint:

<?php

    if (isset($_POST['ids'])) {
        $id_value = $_POST['ids'];
        $state = (int)$_POST['state'];
        $sql_check = "UPDATE toggle SET status= '$state' WHERE id = '$state' ";
        $result_check = mysqli_query($conn,$sql_check);

        if($result_check){
            echo "sucess";
        } else{
            echo "failure";
        }
    }

?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.