Auto submitting Checkbox to save to MySQL - php

I have a page on my website with a 20 checkboxes for each user that has an account, i want to be able to submit the checkbox when it is changed to save it to a DB. Its hard to explain, but i will attach screenshots of the code, HTML output and DB:
PHP code to get the boxes is:
<?php
for ($x = 1; $x <= 16; $x++) {
$result0 = $db->query("SELECT * FROM View WHERE `UserID` LIKE '" . $x . "'");
while($row0 = mysqli_fetch_array($result0)) {
if($row0['20']=="1"){$checked = "checked";}else { $checked = "";}}
echo "<td class=\"align_center\"><input type=\"checkbox\" name=\"20_" . $x . "\" " . $checked . "/>
";}
?>
Im hoping someone can help! PLEASE!
Thanks

The below ajax request would trigger on each checkbox change event.
You will need a PHP script to recieve the data and update your DB.
Look Ajax documentation for more details.
$("input[type='checkbox']").on("change",function(){
$.ajax({
url: "someFileToUpdateDB.php",
data: $("#myForm").serialize(),
success: function(){
console.log("Change saved.");
},
error: function(request,status,error){
console.log("ERROR: "+error);
}
});
});

Related

While loop Mysql updating checkboxes where to start

I have a question how can I update the database if person unchecks or check a checkbox and update the boolean field
in mysql? For days stuck with this problem, because problem I don't know how to make a form or check if
it is validate inside of a while loop here is my code:
<?
$result= mysql_query("SELECT * FROM cars");
$counter = 1;
while($row = mysql_fetch_array($result)) {
echo '<tr>
<td>' . $counter++ . '</td>
<td><input type="checkbox"';
if ($row['show'] == true) {
echo 'checked></td>';
} else {
echo 'unchecked></td>';
}
echo '<td><img src="../xml/'.$row['cars_id'].'-1.JPG" width="120px"></td>';
echo "<td><h3> ", $row['brand']," " . $row['model'], " " . $row['type'],
" € " . $row['price'], " </h3></td>";
echo '</tr>';
}
?>
p.s. I am aware of the mysql to mysqli or pdo but it is a HUGE script...
Oh! No issue here is the solution:
Try using jquery and ajax. For example.
if ( $("#chkbx").prop('checked') == true) {
// do ajax call to update the database
} else {
// do anything if check box is unchecked
}
I am not writing the ajax call just see the jquery ajax manual. If you face any problem come back.
See the above code will create a event listener in the DOM so that when the check box is checked a event should fire.
Now I am extending my code to show you a ajax call.
if ( $("#chkbx").prop('checked') == true) {
$.ajax ({
method: "POST", // type:post or get
url: "test.php", // your php file
data: { name: "test"} // data that I want to send
}).done(function( msg ) {
alert( "Data Saved: " + msg ); // after success show msg
})
}
Now in the php file do the updating part of database or anything you want. The done function will show the msg you returned if the php file execute properly. There are numerous functions in ajax that you can use.Also try to use jquery it's handy and easy to use.
Thank you so much, now I only have to focus on how database works in Ajax
This is what I added and with this I can echo out that it does work now what rest is change the boolean value row['show']
<script type="text/javascript">
function change_checkbox(el){
if(el.checked){
alert("On");
}else{
alert("Off");
}
}
I got pretty far that all is working except for 1 particulair thing.
The problem what I now face is that I cannot send the DATA ID's from the checkbox to the test.php page how can I do this correct this is what I came up with so far:
<?
$result= mysql_query("SELECT * FROM cars");
$counter = 1;
while($row = mysql_fetch_array($result)){
echo '<tr>
<td>' . $counter++ . '</td>
<td><input id="'.$row['cars_id'].'" onchange="change_checkbox(this)" type="checkbox"';
if ($row['toon'] == true){
echo 'checked></td>';
}else
{
echo 'unchecked></td>';
}
echo '<td><img src="../xml/'.$row['cars_id'].'-1.JPG" width="120px"></td>';
echo "<td><h3> ", $row['brand']," " . $row['model'], " " . $row['type'], " € " . $row['price'], " </h3></td>";
echo '</tr>';
}
?>
</tbody>
</table>
</section>
<script type="text/javascript">
function change_checkbox(el){
var id = null;
if(el.checked){
alert("On");
$.ajax ({
method: "POST", // type:post or get
url: "test.php", // your php file
data: { id: id } // data that I want to send
}).done(function( msg ) {
alert( "Data Saved: " + msg ); // after success show msg
})
}else{
alert("Off");
$.ajax ({
method: "POST", // type:post or get
url: "test.php", // your php file
data: { name: "test"} // data that I want to send
}).done(function( msg ) {
alert( "Data Saved: " + msg ); // after success show msg
})
}
}

created input form by json doesn't show in $_POST

I use json for retrieving data from database. When I click on an option it retrieves some input form. But when I print $_POST it doesn't show those inputs.
print_r($_POST); // print all except input fields which retrieved from json
My php code:
foreach($html->result() as $row){
$html_input .= '<input name="' . $row->Feature_Eng_Name . '" type="text" style="color:#888" placeholder="'. $row->Feature_Name . '">';
$html_input .= "<br>";
}
$result = array('status' => 'ok', 'content' => $html_input);
echo json_encode($result);
Script:
$(document).ready(function(){
$("#maintype").click(function(){
var base_url = "<?php echo base_url(); ?>" ;
var isOption = $("option:selected").val();
var cat_id = isOption;
if(isOption == ""){
$("#feature_ajax").html("");
}
else{
$.post(base_url + 'administrator/submit_product/ajax_get_feature_by_cat', {cat_id}, function(data){
if(data.status == 'ok'){
//alert("yes");
$('#feature_ajax').html(data.content);
}
else{
$('#feature_ajax').html("");
}
}, "json");
}
});
});
ok after inspecting your code, the problem was your FORM tags. They were being placed in the wrong places. Make sure if you open a form tag inside a div, you need to close it inside that same div, not outside or the DOM will break it.

Retrieve data within <div> tag using Ajax/jQuery (Inline text edit)

I've been working on this problem for a few hours, but there is some mistake somewhere in the javascript file (I believe), but I can't figure it out.
Right now the alert(msg) gives me an Undefined index: headline/text in editPost.php.
The following PHP code is in a file profile.php. I want to retrieve the data within the <div>I want this data</div> tags (i.e. I want to retrieve the data in $row['headline'] and $row['text'].
while ($row = mysqli_fetch_array ($resultPost, MYSQLI_ASSOC)) {
echo '<h1><div contenteditable="true" data-headline="headline" data-id=' . $row['id'] . '>' . $row['headline'] . '</div></h1>';
echo '<p><div contenteditable="true" data-text="text" data-id=' . $row['id'] . '>' . $row['text'] . '</div></p>';
}
This is how I try to retrieve the data (seperate .js file):
$(document).ready(function() {
$('body').on('blur', "div[contenteditable=true]", function() {
var headline = $("div[data-name='headline']:visible").text();
var text = $("div[data-name='text']:visible").text();
$.ajax({
type: 'POST',
url: 'editPost.php',
data: {
content: $.trim($(this).text()),
id: $(this).data('id'),
headline: $(this).data(headline),
text: $(this).data(text),
},
success: function(msg) {
alert(msg);
}
});
});
});
The function above then posts the data to editPost.php, which submits the data to a database. Below is a snippet of how I do that:
$headline = $_POST['headline'];
$text = $_POST['text'];
$id = $_POST['id'];
$sql = "UPDATE blogpost SET headline = '$headline', text = '$text', edit_time = NOW(6) WHERE id = '$id'";
In the current state, when the data is sent to the database, it finds the correct table (using the id), and inserts "" in both the headline and text fields, but it updates the edit_time correctly.
Thank you!
I took a break for a few hours, and came back with more thoughts on how to solve it. After a little tweaking here and there, I finally did it.
For those of you who visit this thread at a later time, this is what I changed in order for it to work:
My profile.php snippet is now like this (I switched data-headline="headline" to name="headline" etc.):
while ($row = mysqli_fetch_array ($resultPost, MYSQLI_ASSOC)) {
echo '<h1><div contenteditable="true" name="headline" data-id=' . $row['id'] . '>' . $row['headline'] . '</div></h1>';
echo '<p><div contenteditable="true" name="text" data-id=' . $row['id'] . '>' . $row['text'] . '</div></p>';
}
My javascript file now consists of two functions with minor differences (one for each field). Yes, I'm certain there is a better way to solve this:
$(document).ready(function() {
$('body').on('blur', "div[name=headline]", function() {
var headline = $("div[name='headline']:visible").text();
$.ajax({
type: 'POST',
url: 'editPost.php',
data: {
headlineContent: $.trim($(this).text()),
id: $(this).data('id'),
headline: $(this).data(headline),
},
success: function(msg) {
alert(headline);
}
});
});
});
$(document).ready(function() {
$('body').on('blur', "div[name=text]", function() {
var text = $("div[name='text']:visible").text();
$.ajax({
type: 'POST',
url: 'editPost.php',
data: {
textContent: $.trim($(this).text()),
id: $(this).data('id'),
text: $(this).data(text),
},
success: function(msg) {
alert(text);
}
});
});
});
I changed how the elements were targeted, so targeting one element wouldn't duplicate the content over to the other element.
Finally, in my editPost.php file, I added a check to see whether or not a variable is empty. If it is empty, that means the element didn't get updated, hence why it only updates the other element.
$headline = $_POST['headlineContent'];
$text = $_POST['textContent'];
$id = $_POST['id'];
if (!empty($headline)) {
$sql = "UPDATE blogpost SET headline = '$headline', edit_time = NOW(6) WHERE id = '$id'";
} elseif (!empty($text)) {
$sql = "UPDATE blogpost SET text = '$text', edit_time = NOW(6) WHERE id = '$id'";
}
As you can see, the code itself is far from perfect (pretty horrible actually), but it works for now. I'll definitely try to improve on it in the future, but any feedback would be appreciated (I am aware this is not the place for codereview).

send data on button click from javascript to database

So I have a php page that gets data from database and displays a table. Each td symbolises a seat in a movie theater. What i want to do is when a user clicks on one or more tds, and clicks send, the status column for each td in the database changes to 1 from 0(default). When the database is accessed next time, the td's with status=1 have a different color.
My code upto now is:
<div id="screen">SCREEN</div>
<div id="Seatings">
<?php echo "<table border='1'>
<tr>
<th>Seating</th>
</tr>";
$count=0;
echo "<tr>";
echo"<td id='Seat_rn'>A</td>";
while($row = mysql_fetch_array($sql))
{
if($count<10){
echo "<td id='Seat_A' class='count'>" . $row['Seat'] . "</td>";
}
$count++;
}
echo "</tr>";
$sql=mysql_query("SELECT * FROM Seating_para_20 Where Seat > '10'");
echo "<tr>";
echo"<td id='Seat_rn'>B</td>";
while($row = mysql_fetch_array($sql))
{
if($count>=10){
echo "<td id='Seat_B' class='count'>" . $row['Seat'] . "</td>";
}
$count++;
}
echo"</tr>";
echo "</table>";
?>
</div>
<input type="button" value="Done" name="done" onclick="window.close()">
My jquery code is:
$("td #Seat_A").click(function(){
$(this).css("background", "red");
});
$("td #Seat_B").click(function(){
$(this).css("background", "red");
});
$(document."done").click(function(){
alert(price:750 Baht);
})
I am nowhere near what i want and I'm sorry if any of my code is "amatuer-ish" but I am new to this and I have been trying very hard. Would appreciate any help that I can get.
First of all you have to add an ID to every TD on your table, i.e. Seat ID, For example:
echo "<td id='Seat_A' data-seat='". $row['id'] ."'class='count'>" . $row['Seat'] . "</td>";
Then send this ID to your PHP script with Ajax:
$("td #Seat_A").click(function(){
var seat_number = $(this).data("seat");
$.ajax({
type: 'POST',
url: "/take_a_seat.php",
data: 'seat_number='+seat_number,
success: function(data){
$(this).css("background", "red");
}
dataType: "json"
});
});
On the PHP script you have to do what you want to the seat with this ID and return true or false as a result. Let's suppose you have a field named reserved in your database table. You can get the unique ID and update that row to reserved = 1 for example.
Try this easy to use ajax script to accomplish your task
Features: you can show an gif img before send data to db in beforeSend section get response from php file in success section hide img after data inset in db in complete section and show successful or not success msg
var myVar = 'your desire data you want to send to db';
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"myVar="+myVar,
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
Javascript is client side. Your database is server side.. So you have to use php to change your database entries.
In short, if you want to execute PHP stuff without reloading page, than use AJAX. You can use it with your favorite JQuery.
This is an overview. For existing records you should some thing like this
<?php
$count=1;
$res = mysql_query("SELECT * FROM Seating_para_20 Where Seat > '10'");
while($row = mysql_fetch_array($sql)) {
if($row['status']==1) {
$tdcolor = 'red';
} else {
$tdcolor = 'blue';
}
?>
<td id="td-<?php echo $count;?>" sytle="background-color:<?php echo $tdcolor; ?>" onclick="reserveseat(<?php echo $count; ?>);" >
<?php
$count++;
}
?>
For changing after page load you will do ajax operation
<script type="text/javascript" language="javascript">
function reserveseat(count) {
$.ajax({
type: 'POST',
url: "bookseat.php",
data: '',
success: function(data){
$("#td-"+count).css("background-color", "red");
}
});
}
</script>
In bookseat.php you will change the status ... :-) Read about ajax from here . :-)

Can't make autocomplete work with ajax + jQuery

I'm trying to accomplish autocomplete task with the help of ajax (jQuery). Lets have a look at scripts
here is html =>
<input type="text" name="user_key" id="user_key">
here is javascript in the same file =>
<script type="text/javascript">
$(function(){
$("#user_key").autocomplete({
source: function(request,response){
var suggestions = [];
$.ajax({
url: "/ajax/autocomplete.php",
type: "POST",
data: {user_key:$(this).val()},
success: function(result){
$.each(result,function(i,val){
suggestions.push(val.name);
});
},
dataType: "json"
});
response(suggestions);
}
});
});
</script>
and here is php script from autocomplete.php file =>
if (!$connection->connect_errno){
if ($connection->set_charset("utf8")){
if ($r = $connection->query("SELECT name FROM users WHERE name LIKE '" . $_POST['user_key'] . "%'")){
for ($x=0,$numrows = $r->num_rows;$x<$numrows;$x++){
if ($row = $r->fetch_assoc()){
$array[$x] = array("name",$row['name']);
}
}
$r->free();
}
}
}
echo json_encode($array);
PS. It doesn't work. Please help , I've been trying to accomplish this task for the past 2 days,but can't get it to work. Thanks beforehand :)
$array[$x] = array("name",$row['name']);
this is making name and the value from the database both as the elements of the array()
change the code of autocomplete.php to
if (!$connection->connect_errno){
if ($connection->set_charset("utf8")){
if ($r = $connection->query("SELECT name FROM users WHERE name LIKE '" . $_POST['user_key'] . "%'")){
for ($x=0,$numrows = $r->num_rows;$x<$numrows;$x++){
if ($row = $r->fetch_assoc()){
$array[$x] = array("name"=>$row['name']);
}
}
$r->free();
}
}
}
echo json_encode($array);
This will make name as the key for the value fetched from the database
this will help you.
You need to take another look at the autocomplete docs but you will be able to find an answer here: jquery auto-suggestion example doesn't work

Categories