I have an editable input box that saves values to the database and it's working perfectly.
Now I wanted to try adding a datepicker inside that input box so what I did was:
<td contenteditable="true" class="date"><input type="date"></td>
Now when I hit send, I'm getting "All fields are required". Am I doing it wrong?
Here's the whole code for your reference:
<!DOCTYPE html>
<html>
<head>
<title>PC Request Form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Questrial" rel="stylesheet">
<style type="text/css">
body {
font-family: 'Questrial', sans-serif;
}
</style>
</head>
<body>
<br /><br />
<div class="container">
<img src="img/corelogo.png" width="250px; height: 110px;"></img>
<h4>PC Request</h4>
<div class="table-responsive">
<table class="table table-bordered" style="border-radius: 10px;" id="crud_table">
<tr>
<th width="30%">Requested By</th>
<th width="10%">Start Date</th>
<th width="10%">Employee Name</th>
<th width="10%">Position</th>
<th width="10%">Account</th>
<th width="10%">Platform</th>
<th width="45%">Processor</th>
<th width="10%">RAM</th>
<th width="10%">Monitor</th>
<th width="10%">Phone</th>
<th width="10%">Phone Type</th>
<th width="10%">Headset</th>
</tr>
<tr>
<td contenteditable="true" class="reqname"></td>
<td contenteditable="true" class="date"><input type="date"><td>
<td contenteditable="true" class="empname"></td>
<td contenteditable="true" class="position"></td>
<td contenteditable="true" class="account"></td>
<td contenteditable="true" class="platform"></td>
<td contenteditable="true" class="processor"></td>
<td contenteditable="true" class="ram"></td>
<td contenteditable="true" class="monitor"></td>
<td contenteditable="true" class="phone"></td>
<td contenteditable="true" class="phonetype"></td>
<td contenteditable="true" class="headset"></td>
</tr>
</table>
<div align="right">
<button type="button" name="add" id="add" class="btn btn-success btn-xs">+</button>
</div>
<div align="left">
<button type="button" name="save" id="save" class="btn btn-info">Send</button>
</div>
<br />
<div id="inserted_item_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
var count = 1;
$('#add').click(function(){
count = count + 1;
var html_code = "<tr id='row"+count+"'>";
html_code += "<td contenteditable='true' class='reqname'></td>";
html_code += "<td contenteditable='true' class='date'></td>";
html_code += "<td contenteditable='true' class='empname'></td>";
html_code += "<td contenteditable='true' class='position' ></td>";
html_code += "<td contenteditable='true' class='account' ></td>";
html_code += "<td contenteditable='true' class='platform' ></td>";
html_code += "<td contenteditable='true' class='processor' ></td>";
html_code += "<td contenteditable='true' class='ram' ></td>";
html_code += "<td contenteditable='true' class='monitor' ></td>";
html_code += "<td contenteditable='true' class='phone' ></td>";
html_code += "<td contenteditable='true' class='phonetype' ></td>";
html_code += "<td contenteditable='true' class='headset' ></td>";
html_code += "<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-danger btn-xs remove'>-</button></td>";
html_code += "</tr>";
$('#crud_table').append(html_code);
});
$(document).on('click', '.remove', function(){
var delete_row = $(this).data("row");
$('#' + delete_row).remove();
});
$('#save').click(function(){
var reqname = [];
var date = [];
var empname = [];
var position = [];
var account = [];
var platform = [];
var processor = [];
var ram = [];
var monitor = [];
var phone = [];
var phonetype = [];
var headset = [];
$('.reqname').each(function(){
reqname.push($(this).text());
});
$('.date').each(function(){
date.push($(this).text());
});
$('.empname').each(function(){
empname.push($(this).text());
});
$('.position').each(function(){
position.push($(this).text());
});
$('.account').each(function(){
account.push($(this).text());
});
$('.platform').each(function(){
platform.push($(this).text());
});
$('.processor').each(function(){
processor.push($(this).text());
});
$('.ram').each(function(){
ram.push($(this).text());
});
$('.monitor').each(function(){
monitor.push($(this).text());
});
$('.phone').each(function(){
phone.push($(this).text());
});
$('.phonetype').each(function(){
phonetype.push($(this).text());
});
$('.headset').each(function(){
headset.push($(this).text());
});
$.ajax({
url:"insert-message.php",
method:"POST",
data:{reqname:reqname, date:date, empname:empname, position:position, account:account, platform:platform, processor:processor, ram:ram, monitor:monitor, phone:phone, phonetype:phonetype, headset:headset},
success:function(data){
alert(data);
$("td[contentEditable='true']").text("");
for(var i=2; i<= count; i++)
{
$('tr#'+i+'').remove();
}
fetch_item_data();
}
});
});
});
</script>
Insert values code:
<?php
//insert.php
$connect = mysqli_connect("localhost", "root", "", "pcrequesttest");
if(isset($_POST["reqname"]))
{
$reqname = $_POST["reqname"];
$date = $_POST["date"];
$empname = $_POST["empname"];
$position = $_POST["position"];
$account = $_POST["account"];
$platform = $_POST["platform"];
$processor = $_POST["processor"];
$ram = $_POST["ram"];
$monitor = $_POST["monitor"];
$phone = $_POST["phone"];
$phonetype = $_POST["phonetype"];
$headset = $_POST["headset"];
$query = '';
for($count = 0; $count<count($reqname); $count++)
{
$reqname_clean = mysqli_real_escape_string($connect, $reqname[$count]);
$date_clean = mysqli_real_escape_string($connect, $date[$count]);
$empname_clean = mysqli_real_escape_string($connect, $empname[$count]);
$position_clean = mysqli_real_escape_string($connect, $position[$count]);
$account_clean = mysqli_real_escape_string($connect, $account[$count]);
$platform_clean = mysqli_real_escape_string($connect, $platform[$count]);
$processor_clean = mysqli_real_escape_string($connect, $processor[$count]);
$ram_clean = mysqli_real_escape_string($connect, $ram[$count]);
$monitor_clean = mysqli_real_escape_string($connect, $monitor[$count]);
$phone_clean = mysqli_real_escape_string($connect, $phone[$count]);
$phonetype_clean = mysqli_real_escape_string($connect, $phonetype[$count]);
$headset_clean = mysqli_real_escape_string($connect, $headset[$count]);
if($reqname_clean != '' && $date_clean != '' && $empname_clean != '' && $position_clean != '' && $account_clean != '' && $platform_clean != '' && $processor_clean != '' && $ram_clean != '' && $monitor_clean != '' && $phone_clean != '' && $phonetype_clean != '' && $headset_clean != '')
{
$query .= '
INSERT INTO item(reqname, date, empname, position, account, platform, processor, ram, monitor, phone, phonetype, headset)
VALUES("'.$reqname_clean.'", "'.$date_clean.'", "'.$empname_clean.'", "'.$position_clean.'", "'.$account_clean.'", "'.$platform_clean.'", "'.$processor_clean.'", "'.$ram_clean.'", "'.$monitor_clean.'", "'.$phone_clean.'", "'.$phonetype_clean.'", "'.$headset_clean.'");
';
}
}
if($query != '')
{
if(mysqli_multi_query($connect, $query))
{
echo 'Successfuly Sent!';
}
else
{
echo 'Error';
}
}
else
{
echo 'All fields are required!';
}
}
?>
When you're collecting values from your page, you do this:
$('.date').each(function(){
date.push($(this).text());
});
This is working for all of your contenteditable elements, for which their "value" is their text content. But you've now changed your markup here:
<td contenteditable="true" class="date"><input type="date"></td>
You're no longer editing the content of that td, but instead have an input within it. First, remove contenteditable since you're not using it anymore:
<td class="date"><input type="date"></td>
Then in your JavaScript code, instead of looking for the text content of the <td>, look for the value of the <input> therein. Perhaps something like this:
$('.date').each(function(){
date.push($(this).find('input').val());
});
You could change this up in a number of ways, such as moving the class to the <input> and getting the value irectly from that in your .each() loop. But the concept is still the same. You're no longer looking for the text of your <td>, you're now looking for the value of your <input>.
Related
I created a dynamic form to database and everything works perfectly, here's what it looks like:
Dynamic Form
Now I wanted to add a dropdown on each field and now I'm getting errors when I submit it, here's the error:
Error
So basically everything works perfectly until I added the dropdown.
Here's the whole code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container">
<br />
<h2 align="center"></h2>
<br />
<div class="table-responsive">
<table class="table table-bordered" id="crud_table">
<tr>
<th width="30%">Requested By</th>
<th width="10%">Day</th>
<th width="10%">Employee Name</th>
<th width="10%">Position</th>
<th width="10%">Account</th>
<th width="10%">Platform</th>
<th width="45%">Processor</th>
<th width="10%">RAM</th>
<th width="10%">Monitor</th>
<th width="10%">Phone</th>
<th width="10%">Phone Type</th>
<th width="10%">Headset</th>
</tr>
<tr>
<td contenteditable="true" class="reqname"></td>
<td contenteditable="true" class="day"></td>
<td contenteditable="true" class="empname"></td>
<td contenteditable="true" class="position"></td>
<td contenteditable="true" class="account"></td>
<td contenteditable="true" class="platform"></td>
<td contenteditable="true" class="processor"></td>
<td contenteditable="true" class="ram"></td>
<td contenteditable="true" class="monitor"></td>
<td contenteditable="true" class="phone"></td>
<td contenteditable="true" class="phonetype"></td>
<td contenteditable="true" class="headset"></td>
</tr>
</table>
<div align="right">
<button type="button" name="add" id="add" class="btn btn-success btn-xs">+</button>
</div>
<div align="center">
<button type="button" name="save" id="save" class="btn btn-info">Save</button>
</div>
<br />
<div id="inserted_item_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
var count = 1;
$('#add').click(function(){
count = count + 1;
var html_code = "<tr id='row"+count+"'>";
html_code += "<td contenteditable='true' class='reqname'></td>";
html_code += "<td contenteditable='true' class='day'></td>";
html_code += "<td contenteditable='true' class='empname'></td>";
html_code += "<td contenteditable='true' class='position' ></td>";
html_code += "<td contenteditable='true' class='account' ></td>";
html_code += "<td contenteditable='true' class='platform' ></td>";
html_code += "<td contenteditable='true' class='processor' ></td>";
html_code += "<td contenteditable='true' class='ram' ></td>";
html_code += "<td contenteditable='true' class='monitor' ></td>";
html_code += "<td contenteditable='true' class='phone' ></td>";
html_code += "<td contenteditable='true' class='phonetype' ></td>";
html_code += "<td contenteditable='true' class='headset' ></td>";
html_code += "<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-danger btn-xs remove'>-</button></td>";
html_code += "</tr>";
$('#crud_table').append(html_code);
});
$(document).on('click', '.remove', function(){
var delete_row = $(this).data("row");
$('#' + delete_row).remove();
});
$('#save').click(function(){
var reqname = [];
var day = [];
var empname = [];
var position = [];
var account = [];
var platform = [];
var processor = [];
var ram = [];
var monitor = [];
var phone = [];
var phonetype = [];
var headset = [];
$('.reqname').each(function(){
reqname.push($(this).text());
});
$('.day').each(function(){
day.push($(this).text());
});
$('.empname').each(function(){
empname.push($(this).text());
});
$('.position').each(function(){
position.push($(this).text());
});
$('.account').each(function(){
account.push($(this).text());
});
$('.platform').each(function(){
platform.push($(this).text());
});
$('.processor').each(function(){
processor.push($(this).text());
});
$('.ram').each(function(){
ram.push($(this).text());
});
$('.monitor').each(function(){
monitor.push($(this).text());
});
$('.phone').each(function(){
phone.push($(this).text());
});
$('.phonetype').each(function(){
phonetype.push($(this).text());
});
$('.headset').each(function(){
headset.push($(this).text());
});
$.ajax({
url:"insert.php",
method:"POST",
data:{reqname:reqname, day:day, empname:empname, position:position, account:account, platform:platform, processor:processor, ram:ram, monitor:monitor, phone:phone, phonetype:phonetype, headset:headset},
success:function(data){
alert(data);
$("td[contentEditable='true']").text("");
for(var i=2; i<= count; i++)
{
$('tr#'+i+'').remove();
}
fetch_item_data();
}
});
});
function fetch_item_data()
{
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data)
{
$('#inserted_item_data').html(data);
}
})
}
fetch_item_data();
});
</script>
and this is what I did for the dropdown:
<td contenteditable="true" class="platform">
<select>
<option value="Desktop">Desktop</option>
<option value="Laptop">Laptop</option>
</select>
</td>
and here's my DB schema in case you need it:
DB Schema
I am new in php. I trying to know Multiple Inline Insert into Mysql using Ajax JQuery in PHP.
Then I follow this tutorial on "webslesson". My all codes and database are Ok as like as webslesson web tutorial . But my save button doesn't work and don't send any data in my database and also not shown any error....
index.php
<!DOCTYPE html>
<html>
<head>
<title>Multiple Inline Insert into Mysql using Ajax JQuery in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container">
<br />
<h2 align="center">Multiple Inline Insert into Mysql using Ajax JQuery in PHP</h2>
<br />
<div class="table-responsive">
<table class="table table-bordered" id="crud_table">
<tr>
<th width="30%">Item Name</th>
<th width="10%">Item Code</th>
<th width="45%">Description</th>
<th width="10%">Price</th>
<th width="5%"></th>
</tr>
<tr>
<td contenteditable="true" class="item_name"></td>
<td contenteditable="true" class="item_code"></td>
<td contenteditable="true" class="item_desc"></td>
<td contenteditable="true" class="item_price"></td>
<td></td>
</tr>
</table>
<div align="right">
<button type="button" name="add" id="add" class="btn btn-success btn-xs">+</button>
</div>
<div align="center">
<button type="button" name="save" id="save" class="btn btn-info">Save</button>
</div>
<br />
<div id="inserted_item_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
var count = 1;
$('#add').click(function(){
count = count + 1;
var html_code = "<tr id='row"+count+"'>";
html_code += "<td contenteditable='true' class='item_name'></td>";
html_code += "<td contenteditable='true' class='item_code'></td>";
html_code += "<td contenteditable='true' class='item_desc'></td>";
html_code += "<td contenteditable='true' class='item_price' ></td>";
html_code += "<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-danger btn-xs remove'>-</button></td>";
html_code += "</tr>";
$('#crud_table').append(html_code);
});
$(document).on('click', '.remove', function(){
var delete_row = $(this).data("row");
$('#' + delete_row).remove();
});
$('#save').click(function(){
var item_name = [];
var item_code = [];
var item_desc = [];
var item_price = [];
$('.item_name').each(function(){
item_name.push($(this).text());
});
$('.item_code').each(function(){
item_code.push($(this).text());
});
$('.item_desc').each(function(){
item_desc.push($(this).text());
});
$('.item_price').each(function(){
item_price.push($(this).text());
});
$.ajax({
url:"insert.php",
method:"POST",
data:{item_name:item_name, item_code:item_code, item_desc:item_desc, item_price:item_price},
success:function(data){
alert(data);
$("td[contentEditable='true']").text("");
for(var i=2; i<= count; i++)
{
$('tr#'+i+'').remove();
}
fetch_item_data();
}
});
});
function fetch_item_data()
{
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data)
{
$('#inserted_item_data').html(data);
}
})
}
fetch_item_data();
});
</script>
insert.php
<?php
//insert.php
$connect = mysqli_connect("127.0.0.1", "root", "", "testing4");
if(isset($_POST["item_name"]))
{
$item_name = $_POST["item_name"];
$item_code = $_POST["item_code"];
$item_desc = $_POST["item_desc"];
$item_price = $_POST["item_price"];
$query = '';
for($count = 0; $count<count($item_name); $count++)
{
$item_name_clean = mysqli_real_escape_string($connect, $item_name[$count]);
$item_code_clean = mysqli_real_escape_string($connect, $item_code[$count]);
$item_desc_clean = mysqli_real_escape_string($connect, $item_desc[$count]);
$item_price_clean = mysqli_real_escape_string($connect, $item_price[$count]);
if($item_name_clean != '' && $item_code_clean != '' && $item_desc_clean != '' && $item_price_clean != '')
{
$query .= '
INSERT INTO item(item_name, item_code, item_description, item_price)
VALUES("'.$item_name_clean.'", "'.$item_code_clean.'", "'.$item_desc_clean.'", "'.$item_price_clean.'");
';
}
}
if($query != '')
{
if(mysqli_multi_query($connect, $query))
{
echo 'Item Data Inserted';
}
else
{
echo 'Error';
}
}
else
{
echo 'All Fields are Required';
}
}
?>
fetch.php
<?php
//fetch.php
$connect = mysqli_connect("127.0.0.1", "root", "", "testing4");
$output = '';
$query = "SELECT * FROM item ORDER BY item_id DESC";
$result = mysqli_query($connect, $query);
$output = '
<br />
<h3 align="center">Item Data</h3>
<table class="table table-bordered table-striped">
<tr>
<th width="30%">Item Name</th>
<th width="10%">Item Code</th>
<th width="50%">Description</th>
<th width="10%">Price</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["item_name"].'</td>
<td>'.$row["item_code"].'</td>
<td>'.$row["item_description"].'</td>
<td>'.$row["item_price"].'</td>
</tr>
';
}
$output .= '</table>';
echo $output;
?>
This is my database......
item.sql
--
-- Database: `testing4`
- -
-- --------------------------------------------------------
--
-- Table structure for table `item`
--
CREATE TABLE `item` (
`item_id` int(11) NOT NULL,
`item_name` varchar(250) NOT NULL,
`item_code` varchar(250) NOT NULL,
`item_description` text NOT NULL,
`item_price` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
here I am going to delete the database record, when i delete the record, the record deletes successfully but it dosen't reload the insert_search page it displays the result and deleted result will not go, so i need to type every time insert_search in url to get the updated result, please can u tell me where i need to reload the page and how to implement it, thank you in advance...
<?php
$user = "root";
$server = "localhost";
$password = "";
$db = "coedsproddb1";
$dbconn = mysql_connect($server, $user, $password);
mysql_select_db($db, $dbconn);
?>
<html>
<head>
<title>Insert</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.12.4.js"></script>
<script src="js/jquery-ui.js"></script>
<style>
#display {
color: red;
font-size: 12px;
text-align: center;
}
.logo {
padding: 5px;
float: left;
}
header {
background-color: #074e7c;
height: 60px;
width: 100%;
text-align: center;
color: white;
font-size: 40px;
}
#wrap {
text-align: center;
}
</style>
</head>
<body>
<header><img src="images/ipoint.png" class="logo" /> USER REGISTRATION</header>
<div class="container">
<h1 style="text-align:center">ADDING THE USER DETAILS</h1>
<form name="useradd" id="useradd" action="#" method="post">
<table align='center' border='1'>
<tr>
<td>
<label for="userName">UserName</label>
</td>
<td>
<input id="userName" name="userName" type="text" />
</td>
</tr>
<tr>
<td>
<label for="userEmail">Email</label>
</td>
<td>
<input id="userEmail" name="userEmail" type="text" />
</td>
</tr>
<tr>
<td>
<label for="userPassword">password</label>
</td>
<td>
<input id="userPassword" name="userPassword" type="password" />
</td>
</tr>
</table>
<br>
<div id="wrap">
<input type="submit" name="add" value="add" id="add">
<input type="submit" name="update" value="update" id="update">
</div>
</form>
<div id="display">
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function(e) {
var userName = $("#userName").val();
var userEmail = $("#userEmail").val();
var userPassword = $("#userPassword").val();
var dataString = 'userName=' + userName + '&userEmail=' + userEmail + '&userPassword=' + userPassword;
alert(dataString);
if (userName == "" || userEmail == "" || userPassword == "") {
document.getElementById("display").innerHTML = "Please Enter The Fields";
} else if (!validate1($.trim(userName))) {
document.getElementById("display").innerHTML = "Please Enter The Valid UserName";
document.getElementById("display").focus();
} else if (!ValidateEmail($.trim(userEmail))) {
document.getElementById("display").innerHTML = "Please Enter The Valid Emailid";
document.getElementById("display").focus();
} else {
$.ajax({
type: "POST",
url: "insert.php",
data: dataString,
cache: false,
success: function(result) {
//alert("submitted"+result);
$('#display').html(result);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
e.preventDefault();
});
function validate1(userName) {
var u = userName;
var filter = /^[a-zA-Z0-9]+$/;
if (filter.test(u)) {
return true;
} else {
return false;
}
}
function ValidateEmail(userEmail) {
var e = userEmail;
var filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (filter.test(e)) {
return true;
} else {
return false;
}
}
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#update").click(function(e) {
alert("hi");
var userName = $("#userName").val();
var userEmail = $("#userEmail").val();
var userPassword = $("#userPassword").val();
var dataString = 'userName=' + userName + '&userEmail=' + userEmail + '&userPassword=' + userPassword;
alert(dataString);
if (userEmail == "" || userPassword == "") {
document.getElementById("display").innerHTML = "Please Enter The Fields";
} else {
$.ajax({
type: "POST",
url: "user_update.php",
data: dataString,
cache: false,
success: function(result) {
//alert("submitted"+result);
$('#display').html(result);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
e.preventDefault();
});
});
</script>
</body>
</html>
insert.php
<html>
<head>
<title>Insertion</title>
</head>
<body>
<div id="display">
<?php
include('db.php');
$userName = mysql_real_escape_string($_POST['userName']);
$userEmail = mysql_real_escape_string($_POST['userEmail']);
$userPassword = mysql_real_escape_string($_POST['userPassword']);
$regDate = date("Y-m-d");
function generateCode($characters)
{
$possible = '23456789abcdefghjkmnpqrstuvwxyz';
$code = '';
$i = 0;
while ($i < $characters) {
$code .= substr($possible, mt_rand(0, strlen($possible) - 1), 1);
$i++;
}
return $code;
}
$registration_key = generateCode(10);
$str = "insert into coeds_user(userName,userEmail,userPassword,regDate,registration_key) values('$userName','$userEmail','$userPassword','$regDate','$registration_key')";
echo $str;
$query = mysql_query($str);
if ($query) {
$display = "Success";
} else {
$display = "Failed";
}
$string = "select * from coeds_user";
$query2 = mysql_query($string);
$display .= "<table border='1'>";
$display .= "<tr><th>UserId</th><th>UserName</th><th>UserEmail</th><th>UserPassword</th><th>RegDate</th><th>RegistrationKey</th></tr>";
while ($result = mysql_fetch_array($query2)) {
$display .= "<tr>";
$display .= "<td>" . $result['userId'] . "</td>";
$display .= "<td>" . $result['userName'] . "</td>";
$display .= "<td>" . $result['userEmail'] . "</td>";
$display .= "<td>" . $result['userPassword'] . "</td>";
$display .= "<td>" . $result['regDate'] . "</td>";
$display .= "<td>" . $result['registration_key'] . "</td>";
$display .= "<td><a href='user_update.php?user_Id=" . $result['userId'] . "'>Edit</a></td>";
$display .= "<td><a href='user_delete.php?user_Id=" . $result['userId'] . "'>Delete</a></td>";
$display .= "</tr>";
}
$display .= "</table>";
location . reload();
echo $display;
?>
</div>
</body>
</html>
user_delete.php
<html>
<head>
<title>Deletion</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.12.4.js"></script>
<script src="js/jquery-ui.js"></script>
<style>
#display {
color: red;
font-size: 12px;
text-align: center;
}
.logo {
padding: 5px;
float: left;
}
header {
background-color: #074e7c;
height: 60px;
width: 100%;
text-align: center;
color: white;
font-size: 40px;
}
#wrap {
text-align: center;
}
</style>
</head>
<body>
<header> <img src="images/ipoint.png" class="logo" /> USER REGISTRATION</header>
<div class="container">
<h1 style="text-align:center">DELETE WINDOW</h1>
<div id="display">
<?php
include('db.php');
if (isset($_GET['user_Id'])) {
$userid = $_GET['user_Id'];
}
?>
<form action="user_delete.php" name="user_delete" method="post">
<input type="hidden" name="user_Id" id="user_Id" value="<?php
if (isset($userid))
echo $userid;
?>">
<?php
include('db.php');
$s = "delete from coeds_user where userId=$userid";
$query3 = mysql_query($s);
if ($query3) {
$display = "Delete Is Successful";
} else {
$display = "Delete Is Unsuccessful";
}
$string = "select * from coeds_user";
$query5 = mysql_query($string);
$display .= "<table border='1'>";
$display .= "<tr><th>UserId</th><th>UserName</th><th>UserEmail</th><th>UserPassword</th><th>RegistrationDate</th><th>RegistrationKey</th></tr>";
while ($res1 = mysql_fetch_array($query5)) {
$display .= "<tr>";
$display .= "<td>" . $res1['userId'] . "</td>";
$display .= "<td>" . $res1['userName'] . "</td>";
$display .= "<td>" . $res1['userEmail'] . "</td>";
$display .= "<td>" . $res1['userPassword'] . "</td>";
$display .= "<td>" . $res1['regDate'] . "</td>";
$display .= "<td>" . $res1['registration_key'] . "</td>";
}
echo $display;
?>
</div>
</form>
</div>
</body>
</html>
user_update.php
<html>
<head>
<title>Updation</title>
</head>
<body>
<div id="display">
<?php
include('db.php');
if (isset($_GET['user_Id'])) {
$userid = $_GET['user_Id'];
echo $userid;
$s = "select * from coeds_user where userId=$userid";
echo $s;
$query1 = mysql_query($s);
$res = mysql_fetch_array($query1);
?>
<input type="hidden" name="userPassword" id="userPassword">
<input type="hidden" name="userEmail" id="userEmail">
<form action="user_update.php" name="user_update" method="post">
<input type="hidden" name="user_Id" id="userId" value="<?php
if (isset($userid))
echo $userid;
?>">
<table align='center' border='1'>
<tr>
<td>
<label for="userName">UserName</label>
</td>
<td>
<input id="userName" name="userName" type="text" value="<?php
echo $res['userName'];
?> " />
</td>
</tr>
<tr>
<td>
<label for="userEmail">Email</label>
</td>
<td>
<input id="userEmail" name="userEmail" type="text" value="<?php
echo $res['userEmail'];
?> " />
</td>
</tr>
<tr>
<td>
<label for="userPassword">password</label>
</td>
<td>
<input id="userPassword" name="userPassword" type="password" value="<?php
echo $res['userPassword'];
?> " />
</td>
</tr>
</table>
<input type="submit" name="modify" id="modify" value="modify">
<?php
}
include('db.php');
if (isset($_POST['user_Id'])) {
$userid = $_POST['user_Id'];
echo $userid;
}
if (isset($_POST['modify'])) {
echo $userid;
$userName = mysql_real_escape_string($_POST['userName']);
$userEmail = mysql_real_escape_string($_POST['userEmail']);
$userPassword = mysql_real_escape_string($_POST['userPassword']);
$string = "update coeds_user set userName='$userName',userEmail='$userEmail', userPassword='$userPassword' where userId=$userid";
echo $string;
$query = mysql_query($string);
if ($query) {
$display = "Update Successful";
} else {
$display = "Update Failed";
}
$s = "select * from coeds_user";
$query = mysql_query($s);
$display .= "<table border='1'>";
$display .= "<tr><th>UserId</th><th>UserName</th><th>UserEmail</th><th>UserPassword</th><th>RegDate</th><th>RegistrationKey</th></tr>";
while ($res = mysql_fetch_array($query)) {
$display .= "<tr>";
$display .= "<td>" . $res['userId'] . "</td>";
$display .= "<td>" . $res['userName'] . "</td>";
$display .= "<td>" . $res['userEmail'] . "</td>";
$display .= "<td>" . $res['userPassword'] . "</td>";
$display .= "<td>" . $res['regDate'] . "</td>";
$display .= "<td>" . $res['registration_key'] . "</td>";
$display .= "</tr>";
}
$display .= "</table>";
echo $display;
}
?>
</div>
</body>
</form>
</html>
Use
echo "<script>location.replace('user_delete.php');</script>";
instead of header location.
Hope this helps.
I'm trying to print the data from the sql for record purposes but I'm using datatable so when I try to click print, the record doesn't show everything. It only shows the current data from the page 1 of the datatable. How will I do it? Plus, when I tried printing it, the display also shows the include function of the php. Javascript solutions are allowed. Here is my code
<?php include ('sidebar.php'); ?>
<main id="playground">
<?php include ('header.html'); ?>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<section class="panel panel-info">
<header class="panel-heading">
<h4 class="panel-title">List of employees</h4>
</header>
<div class="panel-body">
<?php
include('configuration.php');
$sql = "SELECT firstname, lastname, status, idnumber FROM employees ORDER BY lastname ASC";
$result = $conn->query($sql);
?>
<table class="table table-striped datatable" id="datatables" >
<thead>
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>ID Number</th>
</tr>
</thead>
<?php
if ($result->num_rows > 0) { // output data of each row?>
<tbody>
<button onclick="myFunction()">Print this page</button>
<?php while($row = $result->fetch_assoc()) {
if($row['status']=='p'){
?>
<?php { //this form will display the set of pending applications
echo'<tr>';
echo '<td>' . $row['lastname'] . '</td>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['idnumber'] . '</td>';
echo'</tr>';
}
?>
<?php } //if statement
} //while statement
?>
</tbody>
</table>
<?php
}else {
echo "0 results";
}
?>
</div>
</section>
<!-- end of STRIPED ROWS TABLE -->
</div> <!-- / col-md-12 -->
</div> <!-- / row -->
</div> <!-- / container-fluid -->
</main> <!-- /playground -->
<?php include ('notifications.html'); ?>
<div class="scroll-top">
<i class="ti-angle-up"></i>
</div>
</div> <!-- /animsition -->
<script>
function myFunction() {
window.print();
}
</script>
</body>
</html>
Please use
$('#datatables').DataTable( {
buttons: [
'print'
]
} );
Please check Document and Reference
Use Below 2 functions:
function CreateTableFromObject(tblObj) {
objHeader = JSON.parse(JSON.stringify(tblObj.buttons.exportData()))["header"];
objRows = JSON.parse(JSON.stringify(tblObj.buttons.exportData()))["body"];
//Check If Action Exists in Table and remove it
var index = objHeader.indexOf('Action');
if (index > -1) {
objHeader.splice(index, 1);
}
tblToPrint = "<table style='border: 1px solid black; border-collapse: collapse;'><thead><tr>";
$.each(objHeader, function (key, value) {
tblToPrint += "<th style='border: 1px solid black;'>" + value + "</th>";
});
tblToPrint += "</tr></thead><tbody>";
$.each(objRows, function (key, value) {
tblToPrint += "<tr>";
//If action exists then decrease target by 1
if (index > -1) {
target = value.length - 1;
}else {
target = value.length;
}
for (var i = 0; i < target; i++) {
tblToPrint += "<td style='border: 1px solid black;'>" + value[i] + "</td>";
}
tblToPrint += "</tr>";
});
tblToPrint += "</tbody></table>";
return tblToPrint;
}
function PrintWindowAddParts() {
var tblObj = $("#YourTable").DataTable();
var tblViewRMA = CreateTableFromObject(tblObj);
var printContents = "<div class='dataTables_wrapper form-inline dt-bootstrap'>" + tblViewRMA + "</div>";
var size = 'height=' + $(window).height() + 'px,width=' + $(window).width() + 'px';
var mywindow = window.open('', 'PRINT', size);
mywindow.document.write('<html><head><title>' + "My Title" + '</title>');
mywindow.document.write('</head><body >');
mywindow.document.write('<h4>' + "My Title" + '</h4>');
mywindow.document.write(printContents);
mywindow.document.write('</body></html>');
mywindow.document.close();
mywindow.focus();
mywindow.print();
mywindow.close();
return true;
}
Your Print function is Ready.
previously i have posted one post about the cart page call shopcart.php but it seems that no one really can answer it. whenever i input new quantity and click change quantity button, it seems that the new amount cannot be got and the button has no action, (i really have tried really really hard to find the solution for three wks , uptil now still really cannot find a solution of where the problem is) hope everyone can give me a warm hand to find the problem for me or hints to me
<?php
error_reporting(0);
session_start();
header('Content-type: text/html; charset=utf-8');
include_once('../../xajax_core/xajax.inc.php'); // 引用 xajax
$xajax = new xajax(); // 建立 xajax 物件
// 註冊回應函式
$chaObj=$xajax->registerFunction('change_quantity');
$chaObj->useSingleQuote();
$chaObj->addParameter(XAJAX_FORM_VALUES,'form1');
$xajax->processRequest(); // 處理回應
$xajax->printJavascript();
//---------------------- 自訂函式區 ---------------------
// 負責更改商品數量的回應函式
function change_quantity($form) {
$objResponse = new xajaxResponse(); // 建立回應物件
// 表單中的 Checkbox 屬性為 p_id, 若有勾選, 其值才會傳入
// 所以檢查表單欄位中有 'p_id' 資料, 表示使用者有勾選產品
// 此時才做後續處理
if(isset($form['p_id'])) {
// 逐筆處理每一個被勾選的產品
foreach($form['p_id'] as $p_id) {
// 根據產品的訂購數量決定處理方式
if($form['qua'][$p_id]=='0') {
// 若訂購數量被設為 0, 則將此產品從購物車中移除
unset($_SESSION['cart'][$p_id]);
if(count($_SESSION['cart'])==0) { // 若購物車變成空的
$objResponse-> // 則關閉視窗
script('alert("cart has no items");window.close();');
unset($_SESSION['cart']);
}
else { // 若購物車中還有其它商品
// 將被刪除的產品從網頁中移除
$objResponse->remove($p_id);
// 更新購物車中的金額總計
$objResponse->assign('total','innerHTML',gettotal());
}
}
else if ($form['qua'][$p_id]>0) {
// 若設為大於 0 的值, 則將之設為購物車中的新數量
$_SESSION['cart'][$p_id]['quantity'] = $form['qua'][$p_id];
// 因已修改數量, 所以要更新購物車中的小計及總計金額
$objResponse->assign('sub[' . $p_id . ']', 'innerHTML',
$_SESSION['cart'][$p_id]['quantity'] *
$_SESSION['cart'][$p_id]['price']);
$objResponse->assign('total','innerHTML',gettotal());
}
else {
// 若被設為負值, 則將之回復原本的值
$objResponse->assign('qua[' . $pid . ']', 'innerHTML',
$_SESSION[$pid]['quantity']);
}
}
}
return $objResponse; // 傳回回應物件
} // 回應函式 change_quantity() 結束
// 計算總金額的函式
function getTotal() {
$total = 0;
foreach($_SESSION['cart'] as $p_id => $item)
$total += ($item['quantity'] * $item['price']);
return $total;
}
//---------------------- 購物車 HTML ---------------------
// 目前購物車中有商品, 程式才取出購物車內產品並顯示於網頁
if( !isset($_SESSION['cart']) ) { // 使用者尚未購物
echo "<script>alert(\"you haven't chosen any products\");" .
"window.close();</script>";
exit();
}
?>
<title>購物車內容</title>
<!-- -------------------- 用戶端 JavaScript ------------------ -->
<script type="text/javascript">
// 勾選或取消產品清單中所有產品 checkbox 的函式
function select_all(formName, elementName, selectAllName) {
elem = document.forms[formName].elements[elementName];
if(!elem) // 若找不到元素
return;
else if(elem.length!= null) // 若網頁列出多個產品 (elem 是陣列)
for(var i = 0; i < elem.length; i++)
elem[i].checked =
document.forms[formName].elements[selectAllName].checked;
else
elem.checked =
document.forms[formName].elements[selectAllName].checked;
}
// 將勾選的產品之訂購數量設為0, 再產生非同步要求
function settozero(formName, elementName) {
elem = document.forms[formName].elements[elementName];
if(!elem) // 若找不到元素
return;
else if(elem.length!= null) { // 若網頁列出多個產品 (elem 是陣列)
for(var i = 0; i < elem.length; i++)
if(elem[i].checked) {
var qua =
document.getElementById("qua[" + elem[i].value + "]");
var subtotal = document.getElementById("sub[" + elem[i].value + "]");
qua.value = 0; // 將數量設為 0
subtotal.value = 0;
}
}
else {
var qua = document.getElementById("qua[" + elem.value + "]");
var subtotal = document.getElementById("sub[" + elem.value + "]");
qua.value = 0; // 將數量設為 0
subtotal.value = 0;
}
var total_value = document.getElementById("total");
total_value.value = 0;
<?php $chaObj->printScript(); // 輸出呼叫回應函式的程式碼 ?>
}
</script>
<?php $xajax->printJavaScript('/'); ?>
<!-- ------------------- 購物車表單及表頭 ------------------- -->
<link rel="StyleSheet" type="text/css" href="../module.css" />
<form name="form1" id="form1" method="post" action="checkout.php">
<table width="800" border="0" align="center"
cellspacing="0" cellpadding="2"
style="text-align:center;border:1px solid silver">
<tr><th colspan="7">cart</th></tr>
<tr style="background-color:silver;color:white">
<td height="23" width="80">all
<!----- 呼叫函式選取或取消全部的 checkbox ----->
<input type="checkbox" name="all"
onClick="select_all('form1','p_id[]',this.name);">
</td>
<td height="23" width="460">product name</td>
<td height="23" width="60">unit price</td>
<td width="10" height="23"></td>
<td height="23" width="60">quantity</td>
<td width="10" height="23"></td>
<td width="70" height="23">subtotal</td>
</tr>
<!-- -------------------- 輸出購物車內容 -------------------- -->
<?php
// 呈現購物車表格內容
$total = 0;
foreach($_SESSION['cart'] as $p_id => $item) {
// 將此列的 id 屬性設為 $p_id, 以方便移除產品
echo "<tr id='$p_id'>\n";
echo "<td width='80' height='21'>" .
"<input type='checkbox' name='p_id[]' value='" .
$p_id . "'></td>\n";
echo "<td>" . $item['name'] . "</td>\n";
echo "<td width='60' >" . $item['price'] . "</td>\n";
echo "<td width='10' style='border-width:0'>×</td>\n";
echo "<td width='60'>" .
"<input type='text' name='qua[$p_id]' id='qua[$p_id]'
value='" . $item['quantity'] . "' size='3'></td>";
echo "<td width='10' style='border-width:0'>=</td>\n";
echo "<td width='70' align='right'>" ."<input type='text' size='6' id='sub[$p_id]' value='".($item['quantity'] * $item['price'])."' disabled>"."</td></tr>\n";
}
?>
<tr>
<td align="right" colspan="6">total:</td>
<td align="right" style="border-top:1px solid silver;width:70">
<input type="text" name="total" value="<?php echo gettotal(); // display total amount ?>" id="total">
</td>
</tr>
</table>
<!-- -------------------- cart button -------------------- -->
<table width="800" border="0" align="center">
<tr>
<td height="23" align="center">
<input type="button" name="DEL" value="remove products"
onClick="settozero('form1','p_id[]')">
</td>
<td height="23" align="center">
<input type="button" name="UPD" value="change quantity"
onClick="xajax_change_quantity(xajax.getFormValues('form1'))">
</td>
<td height="23" align="right">
<input type="button" name="CONT" value="continue shopping"
onClick="window.close();">
</td>
<td height="23" align="right">
<input type="button" name="CONT" value="checkout"
onClick="location.href='checkout.php';">
</td>
</tr>
</table>
</form>
isn't "innerHTML"... because tag id="total" is element form input,
correct is "value"
$objResponse->assign('total','innerHTML',gettotal());
correct...
$objResponse->assign('total','value',gettotal());