Autosave checkbox state/value to database

3.9k views Asked by At

Imagine a list of records (drawn from a database) displayed in a table. On earlier views of the table some rows have been selected or unselected and that status is shown with a empty or filled checkbox at the beginning of each record row as required.

I would like the user to be able to click or unclick those checkboxes, and have that revised state auto-saved in the background without needing to click an additional submit button,m but so far I have not found a clear example of what I think ought to be fairly simple with javascript.

I'm new at Javascript and have not yet figured out how to tap the attributes of a control when passing these to a script. I created a code snippet to show the basics of the problem.

function toggle_select(id) {
     // the id number that is passed is the primary key value for the database record
        alert('id '+id+' was clicked'); //this part works, but how to pass the new state to this script?
     // ?? can the function read if the checkbox has been checked or unchecked?
     // if so, then run a background process (ie. php script?) to update that record to the new checked or unchecked state
     // ie. $sql="update recordtable set is_selected='YES/NO' where rec_ID=id limit 1";
  };
<table>
<tr><th colspan="2">SELECT REQUIRED RECORDS</th></tr>
<tr><td><input type="checkbox" name="is_selected" checked onclick="toggle_select(1)" /></td><td>Record 1</td></tr>
<tr><td><input type="checkbox" name="is_selected" onclick="toggle_select(2)" /></td><td>Record 2</td></tr>
<tr><td><input type="checkbox" name="is_selected" checked onclick="toggle_select(3)" /></td><td>Record 3</td></tr>
<tr><td><input type="checkbox" name="is_selected" checked onclick="toggle_select(4)" /></td><td>Record 4</td></tr>
<tr><td><input type="checkbox" name="is_selected" onclick="toggle_select(5)" /></td><td>Record 5</td></tr>
<tr><td><input type="checkbox" name="is_selected" onclick="toggle_select(6)" /></td><td>Record 6</td></tr>
</table>

The bottom line: The goal is to click the checkbox and boom, the selected/unselected state of that record is saved to the database without requiring a full form submit/page reload.

3

There are 3 answers

1
phc_joe On BEST ANSWER

Did it!

Here is the script that works (like a charm!)

if I form my checkbox inputs like so...(much simpler than I thought!)

//when the page loads, the database is tapped and the existing YES/NO value of the selector field is echoed as either checked or (empty string) in the control as it is displayed.  The primary key for the record is used for the checkbox id
//so a checkbox starts out either like this (if the value in the field was YES,
<input type="checkbox" id="649" onclick="toggle_select(649)" checked />
// and like this if it was NO
<input type="checkbox" id="649" onclick="toggle_select(649)" />


<script> 
function  toggle_select(id) {
    var X = document.getElementById(id);
    if (X.checked == true) {
     X.value = "YES";
    } else {
    X.value = "NO";
    }
//var sql="update clients set calendar='" + X.value + "' where cli_ID='" + X.id + "' limit 1";
var who=X.id;
var chk=X.value
//alert("Joe is still debugging: (function incomplete/database record was not updated)\n"+ sql);
  $.ajax({
//this was the confusing part...did not know how to pass the data to the script
      url: 'new_js_saveselect.php',
      type: 'post',
      data: 'who='+who+'&chk='+chk,
      success: function(output) 
      {//alert('success, server says '+output);
      },
      error: function()
      {//alert('something went wrong, save failed');
      }
   });
}
</script>

Oh, and here is the content of the .php script

<?php
foreach($_POST as $fld=>$val) {$$fld=$val;}
$sql="update clients set selected='$chk' where cli_ID='$who' limit 1";
    $link=mysqli_connect("localhost", "user", "pw", "db") or die("Could not connect : " . mysqli_error($link));
    if(mysqli_query($link, $sql)) {echo "OK";} // everything is Ok, the data was inserted
    else {echo "error";} // error happened
mysqli_close($link);
?>
0
David On

AJAX is what you need to accomplish something like this, and you can do it one of two ways.

The first method is the easiest, send the entire form to the server, and update the entire database row.

The second method is a bit harder, but also faster. If you can keep track of which checkbox is which then just send to the server what one has changed, and whether it's on or off, update the appropriate cell from there.

You can learn about how to do the AJAX part Here. It's pretty simple.

2
X Pahadi On

You could have something like: http://jsfiddle.net/eLcjj12s/3/

function toggle_select(id) {
    var url = "http://somewhere.com/save.php?save_id="+id
    $.ajax({
        url: url
    }).done(function() {
        //Work done
        //Do something you like
    });     


  };

And a PHP file for making Database Calls and storage in somewhere.com/save.php

Like:

<?php 
$id = $_GET["id"];
$sql = "UPDATE `id-table` SET `id` = '$id' ....."

//something like that

?>