Warm tip: This article is reproduced from serverfault.com, please click

Update sql database by clicking checkbox without submit button using ajax

发布于 2020-11-27 23:47:04

I am searching for a way to update my sql database without refreshing the page by selecting the checkbox. I am trying to achieve the id to be passed to the dolead.php when the user selects the checkbox and than check whether the id is higher than 0 it must pass the value 1 otherwise the value 0. Afther that check i need the database to be updated with the where clause the posted id. Below my code, what am i doing wrong? i get no errors in my logs and i have the error logging stated as followed: mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

PHP the user is seeing to select the switch box to trigger a select and the jquery to trigger the post.

<head>

<script src="jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="switch.css" type="text/css">


</head>

<body>

    <table id="myTable" align='left' class="deftable">
    <thead>
    <tr>
    <th style="width:10px !important;">!!</th>
    <th>Name</th>
    <th>Notes</th>
    <th>Category</th>
    </tr>
    </thead>
    <tbody>
    
    <?  //Selecteer accounts.
    
    $stmt = $mysqli->prepare("SELECT * FROM account WHERE purpose = 'Crew4' AND level <= ? AND betaald = 'yes' 
    AND group_name = ? AND secret = 'no' ");
    $stmt->bind_param("is", $status,$groupname);
    $stmt->execute();
    $result = $stmt->get_result(); //only works when nd_mysli is set on the server!

    while ($row = $result->fetch_assoc()) {
  ?>  
    <tr>
       <td class="footer"> 
  <label class="switch">
  <input type="checkbox" <?php if($row['do_lead']=='1')  {
                 echo 'checked="checked"';
 } ?> value="<?php echo filter_var($row['id'], FILTER_VALIDATE_INT); ?>" />
  <div class="slider round">
    <span class="on">ON</span>
    <span class="off">OFF</span>
  </div>
</label></td>
    <td><?= htmlspecialchars($row['name']) ?></td>
    <td><?= htmlspecialchars($row['notes']) ?></td>
    <td><?= htmlspecialchars($row['purpose']) ?></td>
 
    
   

    </tr>
    <? } ?>
    </table>


</body>

<script>

$(document).ready(function()

{

var x=$("input[type=checkbox]").length;

$('input[type=checkbox]').on('change', function(i)

{

if($(this).is(':checked'))

{

x-=1;

if(x==0)

{

var val = [];

$(':checkbox:checked').each(function(i)

{

val[i] = $(this).val();

});

var jsonString = JSON.stringify(val);

$.ajax(

{

type: "POST",

url: "dolead.php",

data: {checkbox_value:jsonString},

cache: false,

success: function(data)

{

/* alert if post is success */

}

});

}

}

else

{

x+=1;

}

});

});

</script>

</html>

The dolead.php to retrieve the post value and update the database;

$data = json_decode(stripslashes($_POST['checkbox_value']));

foreach($data as $d){

    if($d > 0){$leadupdate = 1;}
    if($d == ''){$leadupdate = 0;}
        
    $stmt48 = $mysqli->prepare("UPDATE account SET do_lead = ? WHERE id = ? ");
    $stmt48->bind_param("ii", $leadupdate,$d);
    $stmt48->execute();
    $stmt48->close();       

}


?>

PS: the connection file is included but not shown here..

Questioner
newtocss
Viewed
0
KUMAR 2020-11-28 09:38:19

You could add a class to the input and set the value dynamically:-

View:-

<input class="active" type="checkbox" value="$row['do_lead']" >

jQuery/AJAX Call:-

    <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<script type="text/javascript">
$(document).ready(function(e){ 
    $("input.active").click(function() {
    // store the values from the form checkbox, then send via ajax below
    var check_active = $(this).is(':checked') ? 1 : 0;
    var check_id = $(this).attr('value');
    
        $.ajax({
            type: "POST",
            url: "dolead.php",
            data: {id: check_id, active: check_active}
            success: function(response){
                alert('Data Updated Successfully');
    
            }
        });
    return true;
    });
});
</script>

PHP:-

// CLIENT INFORMATION
$active = mysqli_real_escape_string($_POST['active']);
$id = mysqli_real_escape_string($_POST['id']);

//update query.
//execute query.

Note:- for more info regarding click()

https://api.jquery.com/click