After php and mysql outputs a list of data in a table with radio buttons, dropdown boxes and text boxes for each row from the database, I'd like to be able to AJAX update the database onclick of radio button, dropdown boxes or entry of text. This is what I have...
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<?php
require_once 'config.php';
echo '<table style="margin:0 auto;">
<tr>
</tr>';
$sql = "SELECT id, address, suburb, lat, lng, day, date, time FROM addresses";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<tr>
<td><span style="font-weight:bold;">'. $row["address"].' '. $row["suburb"].'</span> <button style="float:right;" type="button">Go</button><br><br>
H<input type="radio" name="home['. $row["id"].']" value="1"/>
NH<input type="radio" name="home['. $row["id"].']" value="2"/>
<select style="padding:1.4px;">
<option></option>
<option>Mo</option>
<option>Tu</option>
<option>We</option>
<option>Th</option>
<option>Fr</option>
<option>Sa</option>
<option>Su</option>
</select>
<input type="text" name="time1" size="2">
<select style="padding:1.4px;">
<option></option>
<option>Mo</option>
<option>Tu</option>
<option>We</option>
<option>Th</option>
<option>Fr</option>
<option>Sa</option>
<option>Su</option>
</select>
<input type="text" name="time2" size="2"><br>
<input style="width:100%; margin-top:5px;" type="text" name="notes" placeholder="Add note">
<br><br>
</td>
<td>
</td>
</tr>';
}
} else {
echo "0 results";
}
echo '</table>';
$conn->close();
?>
<script>
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var home = $(this).val();
$.ajax({
url:"updateaddress.php",
method:"POST",
data:{home:home},
});
});
});
</script>
<?php
// Include config file
require_once 'config.php';
$id = mysqli_real_escape_string($conn, $_POST['id']);
$home = mysqli_real_escape_string($conn, $_POST['home']);
if(isset($_POST["home"])) {
$sql = "UPDATE addresses SET home='$home' WHERE id=$id";
if($conn->query($sql) === TRUE){
} else {
echo "error" . $sql . "<br>".$conn->error;
}
}
mysqli_close($conn);
header("Location: {$_SERVER['HTTP_REFERER']}");
exit;
?>
I can't figure out what I need to do to get this to work.
Please help.
You need to pass the id of the row in to that ajax page...
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<?php
require_once 'config.php';
echo '<table style="margin:0 auto;">
<tr>
</tr>';
$sql = "SELECT id, address, suburb, lat, lng, day, date, time FROM addresses";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<tr>
<td><span style="font-weight:bold;">'. $row["address"].' '. $row["suburb"].'</span> <button style="float:right;" type="button">Go</button><br><br>
H<input type="radio" name="home['. $row["id"].']" id="'. $row["id"].'" value="1"/>
NH<input type="radio" name="home['. $row["id"].']" id="'. $row["id"].'" value="2"/>
<select style="padding:1.4px;">
<option></option>
<option>Mo</option>
<option>Tu</option>
<option>We</option>
<option>Th</option>
<option>Fr</option>
<option>Sa</option>
<option>Su</option>
</select>
<input type="text" name="time1" size="2">
<select style="padding:1.4px;">
<option></option>
<option>Mo</option>
<option>Tu</option>
<option>We</option>
<option>Th</option>
<option>Fr</option>
<option>Sa</option>
<option>Su</option>
</select>
<input type="text" name="time2" size="2"><br>
<input style="width:100%; margin-top:5px;" type="text" name="notes" placeholder="Add note">
<br><br>
</td>
<td>
</td>
</tr>';
}
} else {
echo "0 results";
}
echo '</table>';
$conn->close();
?>
<script>
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var home = $(this).val();
var id = $(this).attr('id');
$.ajax({
url:"updateaddress.php",
method:"POST",
data:{home:home,id:id},
});
});
});
</script>
<?php
// Include config file
require_once 'config.php';
$id = mysqli_real_escape_string($conn, $_POST['id']);
$home = mysqli_real_escape_string($conn, $_POST['home']);
if(isset($_POST["home"])) {
$sql = "UPDATE addresses SET home='$home' WHERE id=$id";
if($conn->query($sql) === TRUE){
} else {
echo "error" . $sql . "<br>".$conn->error;
}
}
mysqli_close($conn);
header("Location: {$_SERVER['HTTP_REFERER']}");
exit;
?>
Related
code:
<script>
$(document).ready(function(){
$(".menu").click(function(){
ids = $('.menu:checked').map(function() {
return this.id;
}).get().join(',');
console.log(ids);
$("#ids").val(ids);
});
});
</script>
<?php
if(isset($_POST['submit']))
{
$adminid = $_POST['admin'];
$menuids = explode(",", $_POST['ids']);
foreach ($menuids as $idd)
{
$sql = "update menu set admin_id = concat(admin_id,'$adminid',',') where id = '$idd'";
$result = mysqli_query($link,$sql);
}
if($result == true)
{
$msg .= "<p style='color:green'>successfull</p>";
}
else
{
$msg .= "<p style='color:red'>error!</p>";
}
}
?>
<form method="post">
<select name="admin" id="admin">
<option value="">---Select Admin---</option>
<?php
$sql = "select * from admin";
$result = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result))
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['firstname']?></option>
<?php
}
?>
</select>
<table>
<tr>
<th>Share</th>
<th>Menu Name</th>
</tr>
<?php
$query = "select * from menu";
$results = mysqli_query($link,$query);
while ($fetch = mysqli_fetch_array($results))
{
?>
<tr>
<td>
<input type="checkbox" class="menu" id="<?php echo $fetch['id']; ?>" name="menuid" />
</td>
<td>
<?php echo $fetch['menu_name']; ?>
</td>
</tr>
<?php
}
?>
</table>
<input type="text" name="ids" id="ids" value=""/>
<input type="submit" name="submit" id="submit" />
</form>
In this code I am update a table having name menu in database. Now, I want to check only those checkbox where admin_id like ,1, or ,2, which is update by query. How can I fix this issue ?please please help.
Thank You
while ($fetch = mysqli_fetch_array($results))
{
?>
<tr>
<td>
<input type="checkbox" class="menu" value="<?php if($fetch['id']==1 or
$fetch['id']==2 ) { echo "checked";} else{} ?>" name="menuid" />
</td>
<td>
<?php echo $fetch['menu_name']; ?>
</td>
</tr>
<?php
}
?>
I have a table of chapters for which I have a delete button for each one. When I am clicking on delete button if the table has more records further the last row of the table gets deleted or the id of row getting pass to the database is wrong.
<!doctype html>
<html>
<head>
<title>Files</title>
</head>
<body>
<form method="post" action="deleteFiles.php" enctype="multipart/form-data">
<style>
td {
text-align: center;
border: 1px solid black;
border-collapse: collapse;
}
</style>
Select rank :
<select name="type" id="type" onchange="this.form.submit()">
<?php if(isset($_POST['type']))
{ ?>
<option value="1" <?php echo($_POST['type']==1?"selected":"");?>>SSgt</option>
<option value="2" <?php echo($_POST['type']==2?"selected":"");?>>TSgt</option>
<option value="3" <?php echo($_POST['type']==3?"selected":"");?>>MSgt</option>
</select>
<br><br>
<?php
}
else
{
?>
<option value="1">SSgt</option>
<option value="2">TSgt</option>
<option value="3">MSgt</option>
</select>
<br><br>
<?php
}
?>
<table id="example" style="width:60%">
<tr>
<th><font size="5">Files</font></th>
</tr>
<?php
?>
<?php
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
$dbh = new PDO('mysql:host=174;dbname=airman', 'airman', 'airma');
if(isset($_POST['action'])) {
$stmt = $dbh->prepare("DELETE FROM `files` WHERE `id`= " . $_POST['id']);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($result) > 0)
{
echo 'row deleted';
}
else{
echo 'row could not delete';
}
}
if(isset($_POST['type']))
{
$stmt = $dbh->prepare("SELECT * FROM files where type = :type");
$stmt->bindParam("type", $_POST['type']);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
}
else{
$stmt = $dbh->prepare("SELECT * FROM files");
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
}
foreach($results as $file)
{
?>
<tr>
<td><?php echo $file['title'];?></td>
<td><input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete">
<input type="submit" id="<?php echo $chap['id']?>" name="edit" value="Edit">
<input type="hidden" name="id" value="<?php echo $file['id']?>" />
</tr>
<?php
}
?>
</table>
</body>
</form>
</html>
<?php
?>
EDIT:
<!doctype html>
<html>
<head>
<title>Video Files</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#form').submit(function(ev) {
$('<input type="hidden">').attr({ name: 'type', value: $("select[name='type']").val() }).appendTo($(event.currentTarget));
}
</script>
<form id="form" method="post" action="deleteVideoFiles.php" enctype="multipart/form-data">
<style>
td {
text-align: center;
border: 1px solid black;
border-collapse: collapse;
}
</style>
<br><br><br><br>
Select rank :
<select name="type" id="type" onchange="this.form.submit()">
<?php if(isset($_POST['type']))
{
/* session_start();
$_SESSION['vidType'] = $_POST['type'];*/
?>
<option value="">Select rank...</option>
<option value="1" <?php echo($_POST['type']==1?"selected":"");?>>SSgt</option>
<option value="2" <?php echo($_POST['type']==2?"selected":"");?>>TSgt</option>
<option value="3" <?php echo($_POST['type']==3?"selected":"");?>>MSgt</option>
</select>
<br><br>
<?php
}
else
{
/* session_start();
$_SESSION['vidType'] = $_POST['type'];*/
?>
<option value="">Select rank...</option>
<option value="1">SSgt</option>
<option value="2">TSgt</option>
<option value="3">MSgt</option>
</select>
<br><br>
<?php
}
?>
<table id="example" style="width:80%">
<tr>
<th><font size="5">Video Files</font></th>
</tr>
<?php
?>
<?php
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
$dbh = new PDO('mysql:host=174.75.54;dbname=handbook', 'airman', 'airman12345');
// $dbh = new PDO('mysql:host=localhost;dbname=handbook', 'siddhi', 'siddhi');
if(isset($_POST['action'])) {
$stmt = $dbh->prepare("DELETE FROM `videos` WHERE `id`= :id");
$stmt->bindParam("id", $_POST['id']);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($result) < 0)
{
echo 'row could not delete';
}
}
if(isset($_POST['type']))
{
if(!empty($_POST['type']))
{
$stmt = $dbh->prepare("SELECT * FROM `videos` where type = :type");
$stmt->bindParam("type", $_POST['type']);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) == 0)
{
echo 'No records available.';
}
}
else{
echo 'empty type';
$stmt = $dbh->prepare("SELECT * FROM `videos`");
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) == 0)
{
echo 'No records available.';
}
}
}
/* elseif(!empty($_SESSION['vidType'])){
echo $_SESSION['vidType'];
echo $_POST['type'];
$stmt = $dbh->prepare("SELECT * FROM `videos` where type = :type");
$stmt->bindParam("type", $_SESSION['vidType']);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) == 0)
{
echo 'No records available.';
}
}*/
else{
$stmt = $dbh->prepare("SELECT * FROM `videos`");
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) == 0)
{
echo 'No records available.';
}
}
foreach($results as $file)
{
?>
<tr>
<td><?php echo $file['title'];?></td>
<td>
<form method="post" action="deleteVideoFiles.php" enctype="multipart/form-data">
<input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete"><br>
<input type="hidden" name="id" value="<?php echo $file['id']?>"/>
</form> <!-- notice how we built different form for every id-->
</td>
</tr>
<?php
}
?>
</table>
</body>
</form>
</html>
<?php
?>
I am sending the id of chapter in for each loop, What is the problem here? Please help thank you..
That is because building the form element this way is going to result for many id inputs inside the same form. something like this
<form>
<input name="id" value="1">
<input name="id" value="2">
</form>
on your server code the php will set $_POST['id'] to the last one which in this case 2. that is why when press delete button and submit the form you delete the next , or last id you have built in your form
If you need your code work the way you want you have to put every id in different form element, Or you will need some javascript work.
I prefer building different form for each record. replace that code
foreach($results as $file)
{
?>
<tr>
<td><?php echo $file['title'];?></td>
<td><input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete">
<input type="submit" id="<?php echo $chap['id']?>" name="edit" value="Edit">
<input type="hidden" name="id" value="<?php echo $file['id']?>" />
</tr>
<?php
}
?>
with something like this
foreach($results as $file)
{
?>
<tr>
<td><?php echo $file['title'];?></td>
<td>
<form method="post" action="deleteFiles.php" enctype="multipart/form-data">
<input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete">
<input type="submit" id="<?php echo $chap['id']?>" name="edit" value="Edit">
<input type="hidden" name="id" value="<?php echo $file['id']?>" />
</form> <!-- notice how we built different form for every id-->
</td>
</tr>
<?php
}
?>
Another note :
$stmt = $dbh->prepare("DELETE FROM `files` WHERE `id`= " . $_POST['id']);
using prepared statements this way makes you still vulnerable to SQL injection.
EDIT(reaction to comments)
to send another input along with the delete forms to the PHP server. you can use JavaScript for that.
1- add that class deleteForm to the delete forms so we can catch those forms and bind to only them.
<form method="post" class="deleteForm" action="deleteVideoFiles.php" enctype="multipart/form-data">
2- edit that script tag in your document
<script>
$(function (){
$('form.deleteForm').submit(function(ev) {
$('<input type="hidden">').attr({ name: 'type', value: $("select[name='type']").val() }).appendTo($(ev.currentTarget));
});
})
</script>
subjects
course
chapters
I want to add 2 dynamic dropdown lists, one is for subjects, and one is for course. When I select subject, courses which is added to that subject should be loaded in the course dropdown list, and then add chapters to that courses.
How do I do that?
Any help would be appreciated.
Here is my code:
<div class="content-form-inner">
<div id="page-heading">Enter the details</div>
<div class="form_loader" id="thisFormLoader"></div>
<div id="error_message"></div>
<form name="thisForm" id="thisForm" action="editchapters.php?mode=<?php echo $_REQUEST['mode']; ?>&id=<?php echo $id; ?>" method="post" enctype="multipart/form-data">
<table border="0" cellpadding="0" cellspacing="0" id="id-form" >
<tr>
<th valign="top" style="width:0%"><span class="required">*</span>Subject</th>
<td style="width: 0%">
<select name="subject_name" class="select-form required " style="color:#000 !important;width:200px !important">
<option value="">Select</option>
<?php
$sql = "select * from mock_subject ";
$res = mysqli_query($dbhandle,$sql);
$numrows =mysqli_num_rows($res);
echo mysql_error();
if($numrows){
while($obj = mysqli_fetch_object($res)){
if($obj->status == 1){
if($subject == $obj->id){
echo '<option value="'.$obj->id.'" selected>'.($obj->subject_name).'</option>';
}
else{
echo '<option value="'.$obj->id.'">'.($obj->subject_name).'</option>';
}
}
}
}
?>
</select>
</td>
<td style="width: 0%;">
<div id="subject_id-error" class="error-inner"></div>
</td>
<td></td>
</tr>
<tr>
<th valign="top" style="width:0%"><span class="required">*</span>Course</th>
<td style="width: 0%">
<select name="course_name" class="select-form required " style="color:#000 !important;width:200px !important">
<option value="">Select</option>
<?php
$sql = "select * from mock_course ";
$res = mysqli_query($dbhandle,$sql);
$numrows =mysqli_num_rows($res);
echo mysql_error();
if($numrows){
while($obj = mysqli_fetch_object($res)){
if($obj->status == 1){
if($course == $obj->id){
echo '<option value="'.$obj->id.'" selected>'.($obj->course_name).'</option>';
}
else{
echo '<option value="'.$obj->id.'">'.($obj->course_name).'</option>';
}
}
}
}
?>
</select>
</td>
<td style="width: 0%;">
<div id="course_id-error" class="error-inner"></div>
</td>
<td></td>
</tr>
<tr>
<th><span class="required">*</span>Chapter</th>
<td><input type="text" name="chapter_name" class="inp-form required" value="<?php echo $chapter;?>" style="color:#000 !important;"></td>
<td>
<div></div>
</td>
</tr>
<tr>
<th> </th>
<td valign="top"><input type="submit" name="submit_button" value="<?php echo $mode=="edit"? "Update" : "Add" ?>" class="form-submit" />
<input type="reset" value="Reset" class="form-reset" />
</tr>
</table>
</form>
<div class="clear"></div>
</div>
One possible solution would, if your data set is comparatively small. Load all the data on page load, and use jquery to get value of dropdown, and based on that formulate the values for the other drop downs.
Second Solution would be to us AJAX and call data from your database for every action. and print using Angular.
I've attached a sample code for that.
This is my_script.js
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$(document).ready(function(){
callSetTimeout();
});
function callSetTimeout(){
setTimeout(function(){
update();
callSetTimeout();
},200);
}
function update(){
$http.get("http://localhost/WhatsOnYourMInd/db.php")
.success(function (response) {$scope.names = response.records;});
}
});
This is for db.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mind";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM data";
$result = $conn->query($sql);
$jsonString=array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
array_push($jsonString,array('id' =>$row['id'],'name' =>$row['name'],'message' =>$row['message']));
}
echo json_encode(array("records"=>$jsonString));
} else {
echo "0 results";
}
$conn->close();
?>
This is for index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Whats on your Mind</title>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<ul id="ajax"></ul>
<div ng-app="myApp" ng-controller="customersCtrl">
<ol>
<li ng-repeat="x in names">
{{ 'Id:'+x.id + ' Name:' + x.name +' Message:'+x.message}}
</li>
</ol>
</div>
<script src="my_script.js"></script>
</body>
</html>
Easiest way of creating dynamic dropdown is by using jquery inside the head tag.
Give onchange() event and guide the data to another page using jquery code, and then link 2 dropdowns. The code I did is like this, which I felt is the easiest way for dynamic dropdowns.
jquery which I included is
<script>
function ajaxDrp(data){
$.ajax({
method: "POST",
url: "chapterDropdown.php",
data: {
id: data
}
}).success(function(data) {
$('#selectCourse').empty();
$('#selectCourse').append(data);
});
}
</script>
#selectCourse is the id I have given to the other dropdown which have to be in sync with the first dropdown.
The given url in the jquery is the path where data of first dropdown is getting collected. In my case, the code is like this:
<?php
$id = $_REQUEST['id'];
$query = "SELECT * FROM `your table name` WHERE subject_id = " . $id;
$result = mysqli_query($dbhandle,$query);
$count = 0;
$option`enter code here` = '';
while($row = mysqli_fetch_assoc($result)) {
$option .= '<option
value="'.$row['id'].'">'.$row['course_name'].'</option>';
}
echo $option;
?>
I need some js/ajax/jquery script saving data to database dynamically when I check the check-box.
the checkboxes at the moment or loaded in next to records and change the variable in the database depending if its checked or not.but i have to reload the page after i select one to save it to the database. i can do everything else but understand how to implement the ajax to this so i don't have to submit the query and refresh the page every time. any help is greatly appreciated.
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['first']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange=" fill_damage (document.form1aa.type.selectedIndex); ">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type=text name="comment" placeholder="Comments Box">
<input type=text name="cost" placeholder="Cost">
<input type="submit" value="Save" name="Save">
</form>
<?php
//Job Status
if(isset($_POST['checkbox'])){$checkbox = $_POST['checkbox'];
if(isset($_POST['activate'])?$activate = $_POST["activate"]:$deactivate = $_POST["deactivate"])
$id = "('" . implode( "','", $checkbox ) . "');" ;
$sql="UPDATE repairs SET status = '".(isset($activate)?'Completed':'In Progress')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Job Status
//Payment Status
if(isset($_POST['paycheck'])){$paycheck = $_POST['paycheck'];
if(isset($_POST['paid'])?$paid = $_POST["paid"]:$unpaid = $_POST["unpaid"])
$id = "('" . implode( "','", $paycheck ) . "');" ;
$sql="UPDATE repairs SET paid = '".(isset($paid)?'Paid':'Unpaid')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Payment Status
//Return Status
if(isset($_POST['retcheck'])){$retcheck = $_POST['retcheck'];
if(isset($_POST['ret'])?$ret = $_POST["ret"]:$unret = $_POST["unret"])
$id = "('" . implode( "','", $retcheck ) . "');" ;
$sql="UPDATE repairs SET ret = '".(isset($ret)?'Retuned':'In Office')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Return Status
$sql="SELECT * FROM $tbl_name";
if(isset($_POST['all'])){
$sql="SELECT * FROM $tbl_name";
}
if(isset($_POST['tpc'])){
$sql="select * from $tbl_name WHERE class LIKE '1%'";
}
if(isset($_POST['drc'])){
$sql="select * from $tbl_name WHERE class LIKE 'D%'";
}
if(isset($_POST['bsc'])){
$sql="select * from $tbl_name WHERE class LIKE 'B%'";
}
$result=mysql_query($sql);
?>
<form name="frmactive" method="post" action="">
<input name="activate" type="submit" id="activate" value="Complete Job" />
<input name="paid" type="submit" id="Payment" value="Payment Status" />
<input name="ret" type="submit" id="ret" value="Returned 2 Student" />
<br />
<a id="displayText" href="javascript:toggle();">Show Extra</a>
<div id="toggleText" style="display: none">
<br />
<input name="unret" type="submit" id="unret" value="In Office" />
<input name="unpaid" type="submit" id="unpaid" value="Not Paid" />
<input name="deactivate" type="submit" id="deactivate" value="In Progress" /></div>
<table width="1000" border="0" cellpadding="3" cellspacing="1">
<thead>
<th width="67" align="center"><strong>Start Date</strong></th>
<th width="50" align="center"><strong>Cases</strong></th>
<th width="34" align="center"><strong>Type</strong></th>
<th width="120" align="center"><strong>Damage</strong></th>
<th width="31" align="center"><strong>Comment</strong></th>
<th width="31" align="center"><strong>Cost</strong></th>
<th width="90" align="center"><strong>Payment Status</strong></th>
<th width="100" align="center"><strong>Returned 2 Student</strong></th>
<th width="100" align="center"><strong>Job Status</strong></th>
</thead>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><? echo $rows['start']; ?></td>
<td><? echo $rows['cases']; ?></td>
<td><? echo $rows['type']; ?></td>
<td width="70"><? echo $rows['damage']; ?></td>
<td width="70"><? echo $rows['comment']; ?></td>
<td><? echo "$"; echo $rows['cost']; ?></td>
<!--Payment Display(Start)-->
<?php
if($rows['paid']=="Paid")
{
?>
<td><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid'];?>
</td>
<?
}
if($rows['paid']=="Unpaid")
{
?>
<td width="21"><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid']; ?>
</td>
<?
}
if($rows['ret']==""){
?>
<td width="50">No Data</td>
<?
}
?>
Do it with jQuery, a simple example could be:
HTML:
<input type="checkbox" name="option1" value="Milk">
<input type="checkbox" name="option2" value="Sugar">
<input type="checkbox" name="option3" value="Chocolate">
JS:
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if(checked){
var value = $(this).val();
$.post('file.php', { value:value }, function(data){
// data = 0 - means that there was an error
// data = 1 - means that everything is ok
if(data == 1){
// Do something or do nothing :-)
alert('Data was saved in db!');
}
});
}
});
PHP: file.php
<?php
if ($_POST && isset($_POST['value'])) {
// db connection
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
// error happened
print(0);
}
mysql_select_db('mydb');
// sanitize the value
$value = mysql_real_escape_string($_POST['value']);
// start the query
$sql = "INSERT INTO table (value) VALUES ('$value')";
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
?>
Simple put...
$('input:checkbox').click( function() {
clicked = $(this).attr('checked');
if (clicked) {
/* AJAX the server to tell them it was clicked. */ }
else {
/* AJAX the server to tell them it was unclicked. */ } } );
I can make this even simpler. first, you need to ad a checkbox!!
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['frist']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange="fill_damage(document.form1aa.type.selectedIndex);">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type="text" name="comment" placeholder="Comments Box">
<input type="text" name="cost" placeholder="Cost">
<input type="checkbox" name="somecheck" onchange="if(this.checked)document.form1aa.submit()">Check this to Save.
<input type="submit" value="Save" name="Save">
</form>
<script type="javascript>
//another function that works for onchange="dosubmit(this)"
//IF you put it after the form.
function dosubmit(el) {
if (el.checked) {
document.form1aa.submit();
}
}
</script>
get rid of the spaces in your onchange events where possible.
If you have dynamic checkbox list and you want to dynamically save the clicked one to database or inserting the unchecked one, here how to do that:
Html/PHP
<?php
// $checklists are models that I am getting from db
$checklists = CheckList::getCheckLists(3);
echo '<ul>';
foreach ($checklists as $checklist) {
$isChecked = $checklist->getAnswer($requestID, $checklist->primaryKey);
$checked = $isChecked ? "checked" : "";
echo '<li>';
echo "<input id='{$checklist->primaryKey}'
name='{$checklist->primaryKey}' type='checkbox' {$checked}
value='{$isChecked}' data-request-id='{$requestID}'>
$checklist->check_list_text";
echo '</li>';
}
echo '</ul>';
?>
Jquery
<script>
$("input[type='checkbox']").on('click', function(){
var checkbox = $(this);
var checked = checkbox.prop('checked');
var checklistId = checkbox.attr("id");
$.ajax({
url:"<?= Url::to(['default/add-checklist-answer']) ?>",
// I don't need to write the type here because I am using Yii Framework
// type: 'post',
data: {
checklistId: checklistId,
requestId: checkbox.data('request-id'),
checked: checked
},
success: function(data) {
//alert(data);
console.log(data.firstMessage)
},
error: function(data) {
// alert(data);
}
});
});
</script>
I hope it will work for MVC users.
I have 2 dropdowns on my HTML page : The first drop down contains the database column names based on which the the second dropdown would be populated i.e.
I have a single table with fields: <Student Name, Degree, City> and following would be the entries;
1. "A", "BS", "New York"
2. "B", "BS", "Chicago"
3. "C", "MS", "Boston"
4. "D", "MS", "New York"
So my first dropdown would contain the column names i.e. "Degree" and "City".
If I select "Degree", the 2nd dropdown should populate "BS" and "MS" and if I select "City", the 2nd dropdown should select "New York", "Boston" and "Chicago".
How can I go about with the implementation?
[Adding my code]:
the changeSecond(first) method remains exactly the same as you suggested
<body>
<form method="POST" action="" name="mainForm">
<table>
<tr>
<td> Filter by: </td>
<td>
<div id="first">
<select onChange="changeSecond(this.value)">
<option value="1">All</option>
<option value="2">Degree</option>
<option value="3">City</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td>
<div id="second">
<select name="val">
<option value=""></option>
</select>
</div>
</td>
</tr>
</table>
</form>
</body>
And this is the second_script.php as you suggested:
<?
$link = mysql_connect("localhost", "root", "");
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_select_db("myDatabase", $link))
{
$first=mysql_real_escape_string($_REQUEST["first"]);
$query="SELECT ".$first." FROM myTable GROUP BY ".$first;
$data=mysql_query($query);
echo "<select id=\"second\">";
while($row=mysql_fetch_row($data))
{
echo "<option value=\"".$row[0]."\">".$row[0]."</option>";
}
echo "</select>";
}
echo mysql_error();
?>
code for the main file in which you want to populate drop down based on other
in below example i show localities in child dropdown for that city that is selected in parent drop down
<script type="text/javascript">
function city_locality(val)
{
// alert (val);
url="<?php echo $this->baseurl ?>/components/com_ezportal/includes/query.php";
data="stid="+val;
$.post(url,data,function(data){
$("#locid").html(data);
});
}
</script>
<select name="filter_1state" id="filter_1state" onChange="city_locality(this.value)">
<option value="0">-- Select City --</option>
<option value="1">Lahore</option>
<option value="2">Karachi</option>
<option value="3">Islamabad</option>
<option value="4">Quetta</option>
<option value="5">Multan</option>
</select>
code for the file query.php
<?php
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('mydatabase');
if (isset($_POST['stid']))
{
$stid = $_POST['stid'];
$query= mysql_query("SELECT id,ezcity FROM tbl_locality WHERE stateid = '".$stid."' GROUP BY ezcity");
?>
<option value="0">-- Select Locality --</option>
<?php
while($row = mysql_fetch_array($query))
{
?>
<option value="<?php echo $row['id']?>"><?php echo $row['ezcity']?> </option>
<?php
}
}
?>
If you want a more dynamic solution (that will accommodate changes to the background DB) you can do something like this on your page:
<script>
function changeSecond(first){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var res=xmlhttp.responseText;
document.getElementById("second").innerHTML=res;
}
}
xmlhttp.open("GET","second_script.php?first="+first,true);
xmlhttp.send();
}
</script>
...
<select onChange="changeSecond(this.value)">
<option value="Degree">Degree</option>
<option value="City">City</option>
</select>
<div id="second"><select><option value=""></option></select></div>
and then a script similar to:
<?php
//database connection
$first=mysql_real_escape_string($_REQUEST["first"]);
$query="SELECT ".$first." FROM tablename GROUP BY ".$first;
$data=mysql_query($query);
echo "<select>";
while($row=mysql_fetch_row($data)){
echo "<option value=\"".$row[0]."\">".$row[0]."</option>";
}
echo "</select>";
?>
I guess for real flexibility you'd also want to dynamically populate that first one using mysql_field_name in another script similar to above
You could either have all the dropdown needed preloaded and hidden, and show them when the 'change' event is triggered in the first dropdown, or have two dropdowns and empty it on that same 'change' event.
If you choose the second approach you should buffer the data to insert in the dropdown list, partially or totally
You can use ajax for this purpose
eg1.html
<html>
<head><title></title>
</head>
<body>
<form method="POST" action="" name="mainForm">
<table>
<tr>
<td> Filter by: </td>
<td>
<div id="first">
<select id="first_dropdown">
<option value="All">All</option>
<option value="Degree">Degree</option>
<option value="City">City</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td>
<div id="second">
<select id="second_dropdown">
</select>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
<script src = "https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#first_dropdown').change(function(){
$.ajax({
'type' : 'post',
'url' : 'getDropdownOptions.php',
'data': 'first=' + $(this).val(),
'success' : function(data) {
$('#second_dropdown').html(data);
}
});
});
});
</script>
getDropdownOptions.php
<?php
$link = mysql_connect("localhost", "root", "");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
if (mysql_select_db("myDatabase", $link)) {
$first = mysql_real_escape_string($_REQUEST["first"]);
$query = "SELECT " . $first . " FROM myTable GROUP BY " . $first;
$data = mysql_query($query);
$rtn_data = '';
while ($row = mysql_fetch_row($data)) {
$rtn_data .= "<option value=\"" . $row[0] . "\">" . $row[0] . " </option>";
}
echo $rtn_data;
exit;
}
echo mysql_error();
?>
Divyesh here, your answer is
==============================
edit.php
==============================
<!-- edit.php -->
<?php
include("config.php");
$id=$_REQUEST['id'];
echo $id;
$query=mysqli_query($con,"SELECT * FROM register r
INNER JOIN country c ON r.cuid = c.cuid
INNER JOIN state s ON r.sid = s.sid
INNER JOIN city ct ON r.cid = ct.cid where id='$id'");
while($r=mysqli_fetch_array($query))
{
$fn=$r['firstname'];
$add=$r['address'];
$gn=$r['gender'];
$hobby=$r['hobby'];
$h=explode(',',$hobby);
$q=array('reading','traveling','cricket','drawing');
$country=$r['cuid'];
$state=$r['sid'];
$city=$r['cid'];
echo $gn;
$edu= $r['education'];
$email=$r['email'];
$pass=$r['password'];
$conpass=$r['conpassword'];
$phno=$r['phoneno'];
}
?>
<html>
<head>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'cuid='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html(html);
}
});
}else{
$('#state').html(html);
$('#city').html(html);
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'sid='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html(html);
}
});
});
</script>
</head>
<body>
<form method="post" action="update.php">
<table border="1" align="center">
<caption>Edit user data</caption>
<tr>
<td>First name</td>
<td><input type="text" name="fn" value="<?php echo $fn;?>"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="add" value="<?php echo $add;?>"></td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="gn" value="male" <?php echo ($gn=='male')?'checked':'' ; ?> size="17">Male
<input type="radio" name="gn" value="female" <?php echo ($gn=='female')?'checked':'' ; ?> size="17">Female
</td>
</tr>
<tr>
<td>Hobby</td>
<td><input type="checkbox" name="hobby[]" value="reading" <?php if(in_array('reading',$h)){echo ("checked:'checked'");}?> >reading
<input type="checkbox" name="hobby[]" value="traveling" <?php if(in_array('traveling',$h)){echo ("checked:'checked'");}?> >traveling
<input type="checkbox" name="hobby[]" value="cricket" <?php if(in_array('cricket',$h)){echo ("checked:'checked'");}?> >cricket
<input type="checkbox" name="hobby[]" value="drawing" <?php if(in_array('drawing',$h)){echo ("checked:'checked'");}?> >drawing</td>
</tr>
<?php
$query = mysqli_query($con,"SELECT * FROM country");
//Count total number of rows
$rowCount = mysqli_num_rows($query);
?>
<td>Country</td>
<td><select name="country" id="country">
<option value="<?php echo $country;?>"><?php echo $country;?></option>
<?php
if($rowCount > 0)
{
while($row = mysqli_fetch_array($query))
{
echo '<option value="'.$row['cuid'].'">'.$row['country'].'</option>';
}
}
else
{
echo '<option value="">Country not available</option>';
}
?>
</select>
</td></tr>
<tr>
<td>State</td>
<td>
<select name="state" id="state">
<option value="<?php echo $state;?>"><?php echo $state;?></option>
</select>
</td></tr>
<tr>
<td>City</td>
<td>
<select name="city" id="city">
<option value="<?php echo $city;?>"><?php echo $city;?></option>
</select>
</td>
</tr>
<tr>
<td>Education</td>
<td><input type="text" name="edu" value="<?php echo $edu;?>"></td>
</tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email;?>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="pass" value="<?php echo $pass;?>"></td>
</tr>
<tr>
<td>Confirm password</td>
<td><input type="text" name="conpass" value="<?php echo $conpass;?>"></td>
</tr>
<tr>
<td>Phone no</td>
<td><input type="text" name="phno" value="<?php echo $phno;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value="<?php echo $id;?>">
<input type="submit" name="update" value="update"></td>
</tr>
</table>
</form>
</body>
</html>
================
<h3>ajaxData.php</h3>
================
<!--ajaxData.php-->
<?php
//Include database configuration file
include("config.php");
if(isset($_POST["cuid"]) && !empty($_POST["cuid"]))
{
//Get all state data
$query = mysqli_query($con,"SELECT * FROM state WHERE cuid = ".$_POST['cuid']."");
//Count total number of rows
$rowCount = mysqli_num_rows($query);
//Display states list
if($rowCount > 0)
{
echo '<option value="">Select state</option>';
while($row = mysqli_fetch_array($query))
{
echo '<option value="'.$row['sid'].'">'.$row['state'].'</option>';
}
}
else
{
echo '<option value="">State not available</option>';
}
}
if(isset($_POST["sid"]) && !empty($_POST["sid"]))
{
//Get all city data
$query = mysqli_query($con,"SELECT * FROM city WHERE sid =".$_POST['sid']."");
//Count total number of rows
$rowCount = mysqli_num_rows($query);
//Display cities list
if($rowCount > 0)
{
echo '<option value="">Select city</option>';
while($row = mysqli_fetch_array($query))
{
echo '<option value="'.$row['cid'].'">'.$row['city'].'</option>';
}
}
else
{
echo '<option value="">City not available</option>';
}
}
?>