Checkbox onChange submit form - php

What i have is a array of items from my mySQL database and each item has a checkbox. i am trying to make it so when you click on the checkbox it will submit the information to the database for the item that got checked or unchecked. have i have it is unchecked = 1 and checked = 0. this is for where i want to display the item.
Now my issue is I can't seem to get anything to submit into my database, I don't understand jQuery enough to be able to write a function for it, so i need some help. here is what i got for my code.
if(isset($_POST['submit'])){
foreach($_POST['id'] as $id){
$value = (isset($_POST['location'][$id]) && $_POST['location'][$id]=="0" ? '0' : '1');
$insert = mysql_query("UPDATE items SET location='$value' WHERE id='$id'") or die('Insert Error: '.mysql_error());
}
}
echo '<form id="form1" method="post"><input type="submit" name="submit" value="Submit">';
$result = mysql_query("SELECT * FROM items")
or die("Query Failed: ".mysql_error());
$counter = 0;
echo '<div class="specialcontainer">';
while($row = mysql_fetch_array($result)){
list($id, $item_info, $item_img, $price, $sale, $location) = $row;
if($location == '0'){
$set_checked = ' checked="checked" ';
}else{
$set_checked = '';
}
if($counter % 5==0) {
echo '</div>';
echo '<div class="specialcontainer">';
}
echo '<div class="special"><img src="../images/items/'.$item_img.'" width="130" /><br />';
echo $item_info.'<br />';
echo 'Reg. $'.$price.'<br />';
echo 'Sale $'.$sale.'<br />';
echo 'Slide Show: <input type="checkbox" id="ch" value="0" name="location['.$id.']"'.$set_checked.' /><br />';
echo '<input type="button" value="Edit" name="edit" onclick="window.location.href=\'specials.php?action=edit&id='.$id.'\'">';
echo '<input type="button" value="Delete" name="Delete" onclick="window.location.href=\'specials.php?action=delete&id='.$id.'\'">';
echo '<input type="hidden" name="id[]" value='.$id.' />';
echo '</div>';
$counter++;
}
echo '</div>';
echo '<input type="submit" name="submit" value="Submit"></form>';
so as you can see, i do have the submit button there, but my plan is to remove it for the onChange submit. I've tried the onchange="this.form.submit();" in the checkbox parameter but it don't work properly. so i just want it to submit anytime a checkbox gets clicked on kinda thing.

Would an Ajax solution like this work?
$('ch').click(function() {
//this is what goes into $_POST
var data = 'id='+ $(this).attr('name') +'&checked=' + $(this).is(':checked');
$.ajax({
//This would be the url that would handle updating the MySQL Record
url: my_mysql_handler.php,
cache: false,
type: 'POST',
data: data,
success: function(response) {
alert(response); //or whatever you want to do with the success/fail notification
}
});
});

You should try document.getElementById('form1').submit() in the onchange method of your checkbox

Related

How do I force a refresh on click on php?

I have two buttons in html which are back and next.
If i click those buttons a variable gets incremented or decremented.
This variable is getting sent to a function.php where there is an sql statement.
The statement is:
select * from x where dimension is = value
How do I refresh the page to show my new table out of my query?
That is my php right here:
function tbl_showPage($page){
global $mysqlhost, $mysqluser, $mysqlpwd, $mysqldb;
$connection=mysqli_connect($mysqlhost, $mysqluser, $mysqlpwd) or die ("Verbindungsversuch fehlgeschlagen");
mysqli_select_db($connection, $mysqldb) or die("Konnte die Datenbank nicht waehlen.");
if($page<1)
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension='1'";
}
elseif($page>9)
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension='9'";
}
else
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension=$page";
}
$quest_query = mysqli_query($connection, $sql_tbl_questions) or die("Anfrage nicht erfolgreich");
$i = 0;
while ($question = mysqli_fetch_array($quest_query)) {
$i++;
echo '<tr>';
echo '<th>'.$i.'</th>';
echo '<th>'.$question['question'].'</th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="0" required></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="2.5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="7.5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="10"></th>';
echo '</tr>';
$dimensions = $question['dimension'];
}
echo '<tr>';
echo '<th></th>';
echo '<th>Kommentar/Ihre Anmerkung</th>';
echo '<th class="text-center" colspan=5><textarea rows=3 cols=50 name="Kommentar"></textarea></th>';
echo '</tr>';
echo '<input type="hidden" name="gesamt" value="'.$i.'">';
echo '<input type="hidden" name="dimensions" value="'.$dimensions.'">';
echo '<input type="hidden" name="size" value="'.$_POST['size'].'">';
echo '<input type="hidden" name="branche" value="'.$_POST['branche'].'">';
}
maybe my var is not beeing passed probably?
The javascript function is looking like that:
<script type="text/javascript">
var ki = kd = 1;
function increase()
{
ki++;
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: ({page:ki}),
success: function(data){
console.log(data);
}
});
window.location.reload();
}
function decrease()
{
kd--;
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: ({page:kd}),
success: function(data){
console.log(data);
}
});
window.location.reload();
}
</script>
I can't really figure out my problem, is my variable which I am generating in the function not passed properly, or is there another problem?
Seems as if you are mixing PHP and javascript here.
Do you have a onClick-function on your button? If you do, and a javascript function is called you can just add window.location.reload(); at the bottom of your javascript function to reload the page.
Tips: Use the edit function on your post and add code related to your problem, then it is easier to get help.
It is easy to make in JavaScript,
function myFunction() {
window.location.reload();
}
And then you just add the function to your button,
<button class="myButton" onclick=myFunction()">Click to reload</button>

How to delete a database record by unchecking a checkbox

<form action="" method="post">
<?php
$sql = "select * from tb_transport";
$query = mysql_query($sql);
$a=1;
while($row=mysql_fetch_array($query))
{
$sql_2="select * from transport_two where transport_id='$row[name]'";
$query_2=mysql_query($sql_2);
$row_2=mysql_fetch_array($query_2);
?>
<input type="checkbox" name="courses[<?php echo $a; ?>][crs]" value="<?php echo $row["name"]; ?>" <?php if($row_2["transport_id"]=="$row[name]") { ?> checked="checked" <?php } ?> />< ?php echo $row["name"]; ?>
<?php
$a=$a+1;
}
?>
<input type="submit" name="save" />
</form>
Here is my form and I'm having a number of checkboxes dependent on my database records.
Here, also I have applied code that if a checkbox value exists in database then it is shown checked.
If I have checked a checkbox, then a row gets inserted with the checkbox value.
Now what I am looking for is that if I uncheck the checked checbox then that database row gets deleted.
How can I do this?
Here is my insertion code:
<?php
if(isset($_POST["save"])) {
$arr = $_POST["courses"];
for ($i = 0; $i < 20; $i++) {
if (!empty($arr[$i]['crs'])) {
$a = $arr[$i]['crs'];
mysql_query("insert into transport_two set transport_id='$a'");
}
}
}
?>
If you want to delete from a database at the moment when a checkbox is marked/unmarked, you need to use JavaScript or jQuery.
If you want to delete from a database at the moment a user clicks on the submit button, you have to send the value to your php - script which updates/deletes from a database.
just give a simple class to checkbox.
<form action="" method="post">
<?php
$sql="select * from tb_transport";
$query=mysql_query($sql);
$a=1;
while($row=mysql_fetch_array($query))
{
$sql_2="select * from transport_two where transport_id='$row[name]'";
$query_2=mysql_query($sql_2);
$row_2=mysql_fetch_array($query_2);
?>
<input type="checkbox" class="deleteFromDb" name="courses[<?php echo $a; ?>][crs]" value="<?php echo $row["name"]; ?>" <?php if($row_2["transport_id"]=="$row[name]") { ?> checked="checked" <?php } ?> /><?php echo $row["name"]; ?>
<?php
$a=$a+1;
}
?>
<input type="submit" name="save" />
</form>
Here click on any check box and jquery check it is check or uncheck. if it uncheck then ajax send request to delete this record from db.
$(document).ready(function(){
$(".deleteFromDb").change(function(e){
if ($(this).prop('checked')==false){
$.ajax({type: "POST",
url: "deleterecord.php",
data: { id:$(this).val().trim() },
success:function(result){
var response = JSON.parse(result);
if(response.error){
//here provide a error msg to user.
alert(response.error);
}
if(response.success){
alert("record deleted");
}
}});
});
}
});
Delete.php
Here perform your delete action.
$id = $_POST['id'];
$strSQL = mysql_query("DELETE FROM `table` WHERE id = ".$id);
if($strSQL){
$result['success'] = "success";
}
else
{
$result['error'] = "try again";
}
echo json_encode($result); die;
Now when you click any checkbox and if it ubcheck, the record will delete from db.

ajax / php form and variable assignment

My goal is to submit a set of variables to my AJAX function from with in a while loop in php. This is my first shot at using AJAX, so please excuse if it is messy, and not close to correct. I appreciate any assistance.
PHP FORM:
x=0;
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$id = $row['col1'];
$ad = $row['col2'];
cho '<form id="msu_form">';
echo "<tr><td>{$ad}</td>";
echo "<td>";
$query2 = "SELECT col1,col2 FROM table WHERE notes = 'x'";
$result2 = mysql_query($query2);
$count2 = mysql_num_rows($result2);
if($count2 > 0)
{
echo '<select class="Primary" name="primary" onchange=doAjaxPost()>';
while($row2 = mysql_fetch_array($result2))
{
echo "<option value=".$row2['col1'].">".$row2['col2']."</option>";
}
echo "</select>";
}else
{
echo "Blah";
}
echo "</td>";
echo "<td>";
$query3 = "SELECT col1,col2 FROM table2 WHERE notes = 'y'";
$result3 = mysql_query($query3);
$count3 = mysql_num_rows($result3);
if($count3 > 0)
{
echo '<select class="Secondary" name="secondary">';
while($row3 = mysql_fetch_array($result3))
{
echo "<option value=".$row3['col1'].">".$row3['col2']."</option>";
}
echo "</select>";
}else
{
echo "Bah";
}
echo "</td>";
echo '<input type="hidden" class="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" class="desc" name="desc" value="'.$ad.'"/>';
//echo '<td>'."<input type='submit' name='btnupdate' value='UPDATE' /></td>";
echo '</form>';
$x = $x+1;
}
So what happens is every time I change any of the "primary" select boxes on the screen, I get the value of the variables on the first line only. I want to receive the values of the form from the select box. I have tested it via a button, that submits the form it is commented out, but that button submits all the correct information to the page, but I don't want to submit the data every time. Is there a way to accomplish my goal?
Thanks - below the ajax if it helps with an answer.
<script>
function doAjaxPost() {
// get the form values
var primary = $(this).val();
var secondary = $(this).parent().next().child('.Secondary').val();
var hidden = $(this).parent().nextAll('.ID').val();
//var desc = $(this).parent().nextAll('#desc').val();
$.ajax({
type: "POST",
url: "functions/database_write.php",
data: $('#msu_form').serialize(),
//data: "Primary="+primary+"&Hidden="+hidden+"&Secondary="+secondary,
success: function(resp){
//we have the response
alert("'" + resp + "'");
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
First, in your php code change the following 4 lines (using id)
echo "<select id=Primary name=primary onchange=doAjaxPost()>";
echo "<select id=Secondary name=secondary>";
echo '<input type="hidden" id="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" id="desc" name="desc" value="'.$ad.'"/>';
to (using class) edited
echo '<select class="Primary" name="primary" onchange="doAjaxPost(this)">'; //added (this)
echo '<select class="Secondary" name="secondary">';
echo '<input type="hidden" class="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" class="desc" name="desc" value="'.$ad.'"/>';
Then, in your javascript code, change
function doAjaxPost() {
var primary = $('#Primary').val();
var secondary = $('#Secondary').val();
var hidden = $('#ID').val();
var desc = $('#desc').val();
to edited
function doAjaxPost(sel) { // added (sel)
var primary = $(sel).val(); //changed to $(sel)
var secondary = $(sel).parent().next().children('.Secondary').val(); //changed to $(sel) and changed to children()
var hidden = $(sel).parent().nextAll('.ID').val(); //changed to $(sel) and changed to nextAll()
var desc = $(sel).parent().nextAll('#desc').val(); //changed to $(sel) and changed to nextAll()
If everything works fine when submitting normally, then probably you are generating the ajax data wrong, instead give your form an id:
echo '<form id="myform">';
Then serialize the form to get the correct data:
function doAjaxPost() {
$.ajax({
type: "POST",
url: "functions/data.php",
data: $('#myform').serialize(),
success: function(resp){
//we have the response
alert("'" + resp + "'");
},
error: function(e){
alert('Error: ' + e);
}
});
}
EDIT Ok you edit has cleared things up a bit, I didn't notice you have multiple forms.
Using the same doAjaxPost function as above, change the data property to:
data: $(this).parents('form').serialize();

Checkbox filetering not working

I have a couple of checkboxes to filter the results from database but I have two problems, the first is that I am using $_POST variable and when I hit refresh I am getting a confirm form submission dialog, which I don't want as the user may hit refresh many times.
The 2nd part of it is that, if I replace $_POSTwith $_GET I don't see the the confirm message but the checkboxes don't work. Anyone has any idea?
<script type="text/javascript">
$(function(){
$('.checkbox').on('change',function(){
$('#form').submit();
});
});
</script>
<form id="id" method="post" action="">
<input type="checkbox" name="new" class="checkbox" <?php if(isset($_POST['new'])) echo "checked"; ?>/> New<br>
<input type="checkbox" name="used" class="checkbox" <?=(isset($_POST['used'])?' checked':'')?>/> Used<br>
<input type="checkbox" name="ref" class="checkbox" <?=(isset($_POST['ref'])?' checked':'')?>/> Refurbished<br>
</form>
if(isset($_GET['page']))
{
$page = $_GET['page'];
}
else
{
$page = 1;
}
$options = array(
'results_per_page' => 2,
'url' => 'products.php?search=' . urlencode($q) . '&page=*VAR*',
'db_handle' => $dbh
);
if (isset($_POST["ref"])) {
$arguments[] = " condition LIKE '%refur%' ";
}
if (isset($_POST["new"])) {
$arguments[] = " condition LIKE '%new%' ";
}
if (isset($_POST["used"])) {
$arguments[] = " condition LIKE '%use%' ";
}
if(!empty($arguments)) {
$str = implode(' or ',$arguments);
$qry = "SELECT * FROM products where " . $str . " ORDER BY id desc";
$paginate = new pagination($page, $qry, $options);
echo $qry;
}
else {
$paginate = new pagination($page, "SELECT * FROM products order by id desc", $options);
}
This is just an idea, using the classical/modern ajax approach for submitting. Assume that this page is called jqpost.php:
<script>
$(document).ready(function () {
$('.checkbox').on('change',function(){
//$('#form').submit();
var formdata = $("#form").serialize();
$.post("jqpost.php", formdata, function(data) {
$("#result").html("Post OK: " + formdata);
});
});
});
</script>
<form id="form" method="post" action="">
<input type="checkbox" name="new" class="checkbox" <?php if(isset($_POST['new'])) echo "checked"; ?>/> New<br>
<input type="checkbox" name="used" class="checkbox" <?=(isset($_POST['used'])?' checked':'')?>/> Used<br>
<input type="checkbox" name="ref" class="checkbox" <?=(isset($_POST['ref'])?' checked':'')?>/> Refurbished<br>
</form>
<div id="result"></div>
<?php
//...
?>
If a user clicks on a checkbox, jQuery will post data to jqpost.php script. In return, #result div will give a status text.
As a result, if the user presses the refresh button on browser, the form is not submitted again and again.

Table with multiple rows and deletions

Ok, so I have an input function that allows me to add items to a database, and displays this as a table. As part of the table, I am trying to add delete and edit buttons.
I am trying to figure out the best way to add delete and edit functionality. I'm thinking for editing, I will have to use Javascript. However, for deletions, I am not sure if I should use PHP, Javascript, or some combination therein.
So far, here's my code:
<html>
<header><title>Generic Web App</title></header>
<body>
<form action="addculture.php" method="POST">
<span><input type="text" size="3" name="id" />
<input type="text" name="culture" />
<input type="submit" value="add" /></span>
</form>
<?php
/* VARIABLE NAMES
*
* $con = MySQL Connection
* $rescult = MySQL Culture Query
* $cultrow = MySQL Culture Query Rows
*/
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("generic");
$rescult = mysql_query("SELECT * FROM culture order by cult_id");
if (!$rescult) {
die('Invalid query: ' . mysql());
}
echo "<table><tbody><tr><th>ID</th><th>Culture Name</th>";
while ($cultrow = mysql_fetch_array($rescult)) {
echo "<tr>" . "<td>" . $cultrow[0] . "</td>" . "<td>" . $cultrow[1] . "</td>" . '<td><button type="button">Del</button></td>' . '<td><button type="button">Edit</button></td>' . "</tr>";
}
echo "</tbody></table>";
?>
</body>
</html>
Currently I have del and edit set as buttons, just for visible reference. What's the best way to deal with a situation where you have multiple buttons like this?
I apologize if my answer is too broad but so is your question.
Both, Editing and Deleting should use a combination of JavaScript and PHP code; for example when the user clicks on the delete button you can send an Ajax request to the server, have the record deleted from the DB and upon successful return from the server-side call, use JavaScript to visually delete the record from the markup. The same would apply to the Edit functionality.
Here's a nice intro on how to perform ajax requests using JQuery:
http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
The first think I would do is add a value and name to the buttons:
<button type="button" value="$cultrow[0]" name="Delete">Delete</button>
<button type="button" value="$cultrow[0]" name="Edit">Edit</button>
The value of the button is going to be the id of the row, and the name is going to be the action that button will do. The next thing I would do is bind those buttons to actions with jquery.
$('button').click(function(){
//determine whether is delete or edit
//Once you determine what action use the id to make the request
//if delete prompt to verify if yes, ajax the server with a delete request
//if edit redirect user to a page that will handle editing of the row edit.php?id=5
});
For deleting row
1 - Make new page name it del_culture.php
session_start();
$id = base64_decode($_GET['id']);
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$q = mysql_query("DELETE FROM culture WHERE cult_id = '".$id."' ");
if($q):
echo "Done";
else:
echo "ERROR";
endif;
2 - in your page add the following code
while ($cultrow = mysql_fetch_array($rescult))
{
echo "<tr>" . "<td>" . $cultrow[0] . "</td>" . "<td>" . $cultrow[1] . "</td>" . '
<td>Delete' . '<td><button type="button">Edit</button></td>' . "</tr>";
}
For Editing a row add link for edit like i did to page name it edit_cult.php
and do the same as you input put the values from database and then update it
This is your javascript
function performAction(action) {
// ASSIGN THE ACTION
var action = action;
// UPDATE THE HIDDEN FIELD
document.getElementById("action").value = action;
switch(action) {
case "delete":
//we get an array with every input contained into the form, and the form have an id
var aryCheck=document.getElementById('adminform').getElementsByTagName('input');
//now we parse them
var elm=null;
var total=0;
for(cptCnt=0;cptCnt<aryCheck.length;cptCnt++) {
elm=aryCheck[cptCnt];
if(elm.type=='checkbox') {
//we have a checkbox here
if(elm.checked==true){
total++;
}
}
}
if(total > 0) {
if(confirm("Are you sure you want to delete the selected records?")) {
// SUBMIT THE FORM
document.adminform.submit();
}
}
else {
alert("You didn't select any records");
}
break;
case "edit":
//we get an array with every input contained into the form, and the form have an id
var aryCheck=document.getElementById('adminform').getElementsByTagName('input');
//now we parse them
var elm=null;
var total=0;
for(cptCnt=0;cptCnt<aryCheck.length;cptCnt++) {
elm=aryCheck[cptCnt];
if(elm.type=='checkbox') {
//we have a checkbox here
if(elm.checked==true){
total++;
}
}
}
if(total > 1) {
alert("You can only edit one record at a time");
}
else if(total == 0) {
alert("You didn't select a record");
}
else {
document.adminform.submit();
}
break;
default:
}
}
and in your form you need something like this
<form id="adminform" name="adminform" action="<?php $_SERVER['REQUEST_URI'] ?>" method="post">
<img src="/admin/images/news.png" alt="news" title="news" />
<input type="button" class="back" id="backbutton" title="go back" onclick="performAction('back');" />
<input type="button" class="delete" id="deletebutton" title="delete" onclick="performAction('delete');" />
<input type="button" class="archive" id="archivebutton" title="archive" onclick="performAction('archive');" />
<input type="button" class="edit" id="editbutton" title="edit" onclick="performAction('edit');" />
<input type="button" class="add" id="addbutton" title="add" onclick="performAction('add');" />
<table id="admintable">
<tr><th class='tdleft'>
<?php
if($err !=0) {
echo"<input type='checkbox' name='all' onclick='checkAll(adminform);' />";
}
echo "</th><th class='tdright'>Title</th></tr>";
$z = 0;
// Iterate through the results
while ($row = $result->fetch()) {
if($z % 2==0) {
//this means if there is a remainder
echo "<tr class='yellow'>\n";
$z++;
} else {
//if there isn't a remainder we will do the else
echo "<tr class='white'>\n";
$z++;
}
echo "<td class='tdleft'><input type='checkbox' name='id[]' value='{$row['id']}' /></td><td class='tdright'><a href='/admin/news/edit-news-".$row['id']."'>{$row['title']}</a></td></tr>";
}
?>
</table>
<input type="hidden" id="action" name="action" value="" />
and at the top of your page before the html put
if($_POST && array_key_exists("action", $_POST)){
// CARRY OUT RELAVANT ACTION
switch($_POST['action']) {
case "edit":
foreach($_POST['id'] as $value) {
$id = $value;
}
header('Location: /admin/blogs/edit-blog-'.$id);
break;
case "delete":
if(!empty($_POST['id'])) {
//do your delete here
}
break;
}
}
}

Categories