I have implemented php function which fetches results and displays them using pagination. Also, I have tried to set on click listener in Jquery to remove active class from the previously selected page and add it to the new one.
However, it correctly switches to a different page but it does not change active class. I am using simplePagination.js
if (isset($_GET["list"])) {
$page = $_GET["list"];
} else {
$page=1;
}
$limit = 10;
$start_from = ($page-1) * $limit;
$query = "SELECT * FROM users WHERE sender_id = '".$_SESSION['id']."' ORDER BY date_time DESC LIMIT $start_from, $limit";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) == 0) {
echo "error";
} else {
echo '<br /><table class="table table-hover">
<thead>
<tr>
<th scope="col"></th>
<th scope="col">Message</th>
<th scope="col">Date</th>
</tr>
</thead>
<tbody>';
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>
<th scope="row"></th>
<td>View Message</td>
<td>'.$row['date_time'].'</td>
</tr>';
}
echo '</tbody>
</table>';
$query = "SELECT COUNT(message_id) FROM inbox";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_row($result);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
$paginationLink = "<nav><ul class='pagination'>";
for ($i = 1; $i <= $total_pages; $i++) {
$paginationLink .= "<li><a href='?page=inbox_sent&list=".$i."'>".$i."</a></li>";
};
echo $paginationLink . "</ul></nav>";
}
And in my Javascript file I have this:
$(document).ready(function(){
$('.pagination').pagination({
items: 50,
itemsOnPage: 10,
cssStyle: 'light-theme',
hrefTextPrefix: '?page=inbox_sent&list='
});
$( ".navlink" ).click(function() {
$(".navlink").removeClass('active');
$(this).addClass('active');
});
});
All results are displayed correctly, but active class of pagination always stays the same.
Related
i want to insert both value and content of dropdown select into a database table. i can insert the value with no problem but i have no idea how to insert the content. i've been searching similar questions and probably it can be done by adding javascript. but i haven't learned about that yet so i have no clue how to use it.
<form action="hitung.php" method="POST" id="formid">
<?php
$query = "SELECT nama FROM alternatif";
$result = mysqli_query($conn, $query);
for ($i=0; $i < $row = mysqli_fetch_array($result) ; $i++) {
?>
<tr>
<th><?php echo $row['nama'] ?></th>
<?php
$select = mysqli_query($conn, "SELECT * FROM kriteria");
$count = mysqli_num_rows($select);
for ($j=0; $j < $count ; $j++) {
?>
<td>
<select class="btn-secondary" name="subkrt[<?php echo $i ?>][<?php echo $j ?>]" required>
<option value="" style="display:none;" required>-Pilih-</option>
<?php
$query = mysqli_query($conn, "SELECT pv_alternatif.pv_subkriteria, subkriteria.nama FROM pv_alternatif INNER JOIN subkriteria ON pv_alternatif.id_alternatif = subkriteria.id WHERE id_kriteria=$j+1");
while ($a = mysqli_fetch_array($query)) {
?>
<option value="<?php echo $a['pv_subkriteria']; ?>"><?php echo $a['nama']; ?></option>
<?php
}
?>
</select>
</td>
<?php
}
}
?>
</tr>
</form>
so both value and content are fetched from two different tables of my database. and hitung.php is code to insert into database.
include 'koneksi.php';
include 'fungsi.php';
$jmlsub = array();
$qwery = mysqli_query($conn, "SELECT nilai FROM pv_kriteria");
while ($row = mysqli_fetch_array($qwery)){
$rows[] = $row['nilai'];
$jmlsub[] = 0;
}
$query = "SELECT nama FROM alternatif";
$result = mysqli_query($conn, $query);
$a = mysqli_query($conn, "SELECT * FROM nilai_alt");
for ($i=0; $i < $row = mysqli_fetch_array($result) ; $i++) {?>
<?php
$select = mysqli_query($conn, "SELECT * FROM kriteria");
$count = mysqli_num_rows($select);
for ($j=0; $j < $count ; $j++) {
if(isset($_POST['subkrt'][$i][$j])){
$matriks[$i][$j] = $_POST['subkrt'][$i][$j] * $rows[$j];
$value = $matriks[$i][$j];
$jmlsub[$i] += $value;
$id_alternatif = getIDAlternatif($i);
$id_kriteria = getKriteriaID($j);
if (mysqli_num_rows($a)==0) {
$b = "INSERT INTO nilai_alt VALUES('',$id_alternatif,$id_kriteria,$value)";
} else {
$b = "UPDATE nilai_alt SET nilai_alternatif=$value WHERE id_alternatif = $id_alternatif AND id_kriteria = $id_kriteria";
}
$rsult = mysqli_query($conn,$b);
if (!$rsult) {
echo "Gagal memasukkan / mengupdate nilai alternatif";
exit();
}
}
}
}
$jmlAlternatif = getJumlahSubKriteria();
for ($i=0; $i < ($jmlAlternatif); $i++) {
$id_alternatif = getIDAlternatif($i);
$query = "INSERT INTO ranking VALUES ($id_alternatif,$jmlsub[$i]) ON DUPLICATE KEY UPDATE nilai=$jmlsub[$i]";
$result = mysqli_query($conn,$query);
if (!$result) {
echo "Gagal mengupdate ranking";
exit();
}
}
header('Location: hasil_subkrt.php');
?>
tables:
Any help will be greatly appreciated. Thanks.
As you said you "can insert the value with no problem", so it is simple to pass all the value and content to the selected option value as a string
using json_encode(...), then in hitung.php you just convert it back to array or object using json_decode(...)
If you have a array, example:
$a = array('pv_subkriteria' => 'the value', 'nama' => 'the name');
Then just
<option value='<?php echo htmlentities(json_encode($a)); ?>'><?php echo $a['nama']; ?></option>
Then in your case in hitung.php,
...
$a = json_decode(html_entity_decode($_POST['subkrt'][$i][$j]), true);
...
More info, generally your code has nested loop and query database in loop, you need to think more about better query way to reduce number of loops to increase performance.
Edited and added an example using some php functions that might help you:
<?php
$a = array('pv_subkriteria' => 'the value', 'nama' => 'the name');
$str = htmlentities(json_encode($a));
$a2 = json_decode(html_entity_decode($str), true);
print_r($a2);
?>
Im trying to add external link to "customer_id" link example has to be like this /edit-customer.php?customer_id=$customer_id(which is link to original customer id) I am creating big detail page most informations its not in the table
I want to add '$' and money format has to be $ 1,250.00. this my code
<script>
$(document).ready(function() {
var dataTable = $('#customer_table').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
url: "serverside/ajax-users.php",
type: "POST"
}
});
$('#customer_table').on('draw.dt', function() {
$('#customer_table').Tabledit({
url: 'serverside/action.php',
dataType: 'json',
columns: {
identifier: [0, 'customer_id'],
editable: [
[1, 'customer_store', '{"1":"B2C","2":"B2B"}'],
[2, 'customer_name'],
[3, 'customer_address'],
[4, 'customer_phone'],
[5, 'customer_email'],
[6, 'customer_status', '{"1":"Inactive","2":"Active"}']
]
},
restoreButton: false,
onSuccess: function(data, textStatus, jqXHR) {
if (data.action == 'delete') {
$('#' + data.customer_id).remove();
$('#customer_table').DataTable().ajax.reload();
}
}
});
});
}); <
/script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<table id="customer_table" class="display nowrap form-inline" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Store ID</th>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
<th>Email</th>
<th>Status</th>
<th>Signing Date</th>
<th>Orders</th>
<th>Total Sales</th>
<th>Detail</th>
</tr>
</thead>
<tbody></tbody>
</table>
//AJAX-USER.PHP
<?php
link db
$column = array("customer_id", "customer_store", "customer_name", "customer_address", "customer_phone", "customer_email", "customer_status", "customer_date", "customer_order", "customer_sale");
$query = "SELECT * FROM customers ";
if(isset($_POST["search"]["value"]))
{
$query .= '
WHERE customer_id LIKE "%'.$_POST["search"]["value"].'%"
OR customer_name LIKE "%'.$_POST["search"]["value"].'%"
OR customer_store LIKE "%'.$_POST["search"]["value"].'%"
OR customer_address LIKE "%'.$_POST["search"]["value"].'%"
OR customer_phone LIKE "%'.$_POST["search"]["value"].'%"
OR customer_email LIKE "%'.$_POST["search"]["value"].'%"
OR customer_sale LIKE "%'.$_POST["search"]["value"].'%"
OR customer_status LIKE "%'.$_POST["search"]["value"].'%"
';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY customer_date DESC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$number_filter_row = $statement->rowCount();
$statement = $connect->prepare($query . $query1);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row['customer_id'];
$sub_array[] = $row['customer_store'];
$sub_array[] = $row['customer_name'];
$sub_array[] = $row['customer_address'];
$sub_array[] = $row['customer_phone'];
$sub_array[] = $row['customer_email'];
$sub_array[] = $row['customer_status'];
$sub_array[] = $row['customer_date'];
$sub_array[] = $row['customer_order'];
$sub_array[] = $row['customer_sale'];
$sub_array[] = $row['customer_detail'];
$data[] = $sub_array;
}
function count_all_data($connect)
{
$query = "SELECT * FROM customers";
$statement = $connect->prepare($query);
$statement->execute();
return $statement->rowCount();
}
$output = array(
'draw' => intval($_POST['draw']),
'recordsTotal' => count_all_data($connect),
'recordsFiltered' => $number_filter_row,
'data' => $data
);
echo json_encode($output);
?>
//ACTION.PHP
<?php
if ($_POST['action']== 'edit') {
$data = array(
':customer_store' => $_POST['customer_store'],
':customer_name' => $_POST['customer_name'],
':customer_address' => $_POST['customer_address'],
':customer_phone' => $_POST['customer_phone'],
':customer_email' => $_POST['customer_email'],
':customer_status' => $_POST['customer_status'],
':customer_id' => $_POST['customer_id']
);
$query = "
UPDATE customers
SET customer_store = :customer_store,
customer_name = :customer_name,
customer_address = :customer_address,
customer_phone = :customer_phone,
customer_email = :customer_email,
customer_status = :customer_status
WHERE customer_id = :customer_id
";
$statement = $connect->prepare($query);
$statement->execute($data);
echo json_encode($_POST);
}
if ($_POST['action'] == 'delete')
{
$query = "
DELETE FROM customers
WHERE customer_id = '".$_POST["customer_id"]."'
";
$statement = $connect->prepare($query);
$statement->execute();
echo json_encode($_POST);
}
?>
My all information here, thank you for your help.
if you need! adding hyperlinks to table column .
I add this code under type:POST in script section
i have 9 table head. i added 1 more 'th' end of the line.
"columnDefs": [ {
"targets": 10,
"data": 0,
"render": function ( data, type, row, meta ) {
return '<center><button class="btn btn-light btn-sm">Detail</button></center>';
}
}]
targets 10 last 'th' ----
data 0 is customer_id.
This is the partial code.
if($_POST["action"] == "fetch_data"){
$output = '';
$query = " SELECT login.user_id, login.username FROM login_details INNER JOIN login ON login.user_id = login_details.user_id WHERE last_status > DATE_SUB(NOW(), INTERVAL 5 SECOND)";
$statement = $conn -> prepare($query);
$statement -> execute();
$result = $statement -> fetchAll();
$count = $statement -> rowCount();
$output .='<div class="table-responsive">
<div align="right">
'.$count.' Users
</div>
<table class="table table-bordered table-hover table-dark">
<tr>
<th width="50%">Username</td>
<th width="10%">Status</td>
<th width="10%">Action</td>
</tr>';
foreach($result as $row){
$status = '';
$current_timestamp = strtotime(date('Y-m-d- H:i:s') . '- 10 second');
$current_timestamp = date('Y-m-d H:i:s', $current_timestamp);
$user_last_activity = get_user_last_activity($row['user_id'], $conn);
if($user_last_activity > $current_timestamp) {
$status = '<span class="label label-success">Online</span>';
} else {
$status = '<span class="label label-danger">Offline</span>';
}
$output .= '<tr> <td>'.$row['username'].' '.count_unseen_message($row['user_id'], $_SESSION['user_id'], $conn).' '.fetch_is_type_status($row['user_id'], $conn).'</td><td>'.$status.'</td><td><button type="button" class="btn btn-info btn-xs start_chat" data-touserid="'.$row['user_id'].'" data-tousername="'.$row['username'].'">Start Chat</button></td></tr>';
}
$output .= '</table></div>';
echo $output;
}
function get_user_last_activity($user_id, $conn) {
$query = "SELECT * FROM login_details WHERE user_id = '$user_id' ORDER BY last_status DESC LIMIT 1";
$statement = $conn -> prepare($query);
$statement -> execute();
$result = $statement -> fetchAll();
foreach($result as $row) {
return $row['last_status'];
}
}
This is the result when it's working. It just shows my online user whereas I want to be able to show both online/offline users at the same time.
Is there something wrong I did?
I have this jQuery form being outputted in a PHP while loop if the button has not previously been clicked and just an image with the value if it has, the function is like facebooks like button where when the user clicks the button the icon changes so its not clickable any longer and the value increments by 1. The form submission works but I cannot seem to update the icon image and value count in the feed without effecting all the other buttons and values in the feed… I tried jQuery replaceWith() but it replaces all the #bumpCont divs in the feed…
index.php
<div class="images">
<?php
while($row = $result2->fetch_assoc()){
$path = $row['path'];
$user = $row['user'];
$id = $row['id'];
$desc = $row['desc'];
$update = $row['update_date'];
$bump = $row['bump'];
$timeFirst = strtotime($date);
$timeSecond = strtotime($update);
$timeSecond = $timeSecond + 86400;
$timer = $timeSecond - $timeFirst;
?>
<?php if(empty($desc)){}else{?><div id="desc"><?php echo $desc;?></div><?php }?>
<img id="pic" src="uploads/<?php echo $path;?>"/>
<div id="userCont">
<div id="user"><a rel="external" href="user_profile.php?user='.$user.'"><?php echo $user;?></a></div>
<div id="timer"><?php echo $timer;?></div>
<?php
if(in_array($path, $mypath)) {
echo '<div id="bumpCont"><img id="bump" style="height:55px;right:8px;top: 2px;position: relative;" src="../img/bumpg.png"/><span id="bumpCount">'.$bump.'</span></div>';
}else{
echo '<form method="post" id="bumpF" data-ajax="false">';
echo '<input name="id" data-ajax="false" id="field_'.$id.'" type="hidden" value="'.$id.'" />';
echo '<div id="bumpCont"><input type="image" style="height:55px;right:8px;top: 2px;position: relative; " id="bump" src="../img/bump.png" id="searchForm" onclick="SubmitForm('.$id.');" value="Send" /><span id="bumpCount">'.$bump.'</span></div>';
echo ' </form>';
}
?>
</div>
<?php
}
?>
//Submit Form
function SubmitForm(id) {
event.preventDefault();
var name = $('#field_'+id).val();
console.log(name);
$.post("bump.php", {name: name},
function(data) {
$( "#bumpCont" ).replaceWith( '<div id="bumpCont"><img id="bump" style="height:55px;right:8px;top: 2px;position: relative;" src="../img/bumpg.png"/><span id="bumpCount">' + data + '</span></div>' );
}
Bump.php -
$id = $_POST['name'];
$sessionUser = $_SESSION['userSession'];
// GET USERNAME
$sql = "SELECT * FROM userbase WHERE user_id='$sessionUser'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$myname = $row['username'];
}
}
$bump = 1;
$sql = "SELECT * FROM images WHERE id=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$bump = $row['bump'];
$path = $row['path'];
$desc = $row['desc'];
$post_user = $row['user'];
$bump++;
}
}
$bumpC = 0;
$sql = "SELECT * FROM bumped WHERE path='$path' AND myname ='$myname'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$bumpC++;
}
}
echo $bump;
if($bumpC >= 1){
}else{
$sql = "INSERT INTO `bumped` ( `myname`,`path`, `description`, `post_user`) VALUES ( '$myname','$path', '$desc', '$post_user')";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "UPDATE images SET update_date='$date' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error updating record: " . $conn->error;
}
$sql = "UPDATE images SET bump=$bump WHERE id=$id";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error updating record: " . $conn->error;
}
}
First look shows me a problem of Elements with same ID in loop.
You could have same class to multiple elements.
<div class="bumpCont"><span class="bumpCount">1</span></div>
<div class="bumpCont"><span class="bumpCount">2</span></div>
Use $(this)
Based on the click on particular element, you can change contents.
$('.bumpCount').click(function(){
$(this).html(parseInt($(this).html) + 1);
});
Hope this helps you.
$('.bumpCount').click(function(){
$(this).html(parseInt($(this).html()) + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bumpCont"><span class="bumpCount">1</span></div>
<div class="bumpCont"><span class="bumpCount">2</span></div>
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 8 years ago.
This page include two web page, insert6.php is using iframe.
This full code of the web site of the page.
form6.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5" />
<title>CCC</title>
<style>
#tlist tr:last-child td {
background-color:#CCCCCC;
}
table{
table-layout: fixed;
}
th, td {
overflow: hidden;
}
#container
{
margin-left:auto;
margin-right:auto;
width:600px;
}
</style>
</head>
<body>
<h3>New Record</h3>
<script language="JavaScript" type="text/javascript">
function addRowToTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// left cell
var cellLeft = row.insertCell(0);
var che = document.createElement('input');
che.type = 'checkbox';
che.id = 'op'+ iteration;
che.name= 'checkbox';
cellLeft.appendChild(che);
// right cell
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.name = 'txtRow[]';
el.id = 'txtRow' + iteration;
el.size = 40;
el.onkeypress = keyPressTest;
cellRight.appendChild(el);
// select cell
var cellRightSel = row.insertCell(2);
var sel = document.createElement('select');
//sel.type = 'text';
sel.name = 'selRow[]';
sel.id = 'selRow' + iteration;
sel.options[0]= new Option("<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
if ($row[$i]=="FF")
echo($row[$i]);
}
}
mysql_free_result($result);
?>");
sel.options[1]= new Option("<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
if ($row[$i]=="DD")
echo($row[$i]);
}
}
mysql_free_result($result);
?>");
sel.options[2]= new Option("<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
if ($row[$i]=="TT")
echo($row[$i]);
}
}
mysql_free_result($result);
?>");
sel.options[3]= new Option("<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
if ($row[$i]=="GG")
echo($row[$i]);
}
}
mysql_free_result($result);
?>");
sel.options[4]= new Option("<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
if ($row[$i]=="RR")
echo($row[$i]);
}
}
mysql_free_result($result);
?>");
sel.options[5]= new Option("<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
if ($row[$i]=="AA")
echo($row[$i]);
}
}
mysql_free_result($result);
?>");
cellRightSel.appendChild(sel);
}
function keyPressTest(e, obj)
{
var validateChkb = document.getElementById('chkValidateOnKeyPress');
if (validateChkb.checked) {
var displayObj = document.getElementById('spanOutput');
var key;
if(window.event) {
key = window.event.keyCode;
}
else if(e.which) {
key = e.which;
}
var objId;
if (obj != null) {
objId = obj.id;
} else {
objId = this.id;
}
displayObj.innerHTML = objId + ' : ' + String.fromCharCode(key);
}
}
function openInNewWindow(frm)
{
// open a blank window
var aWindow = window.open('', 'TableAddRowNewWindow',
'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');
// set the target to the blank window
frm.target = 'TableAddRowNewWindow';
// submit
frm.submit();
}
function validateRow(frm)
{
var chkb = document.getElementById('chkValidate');
if (chkb.checked) {
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length - 1;
var i;
for (i=1; i<=lastRow; i++) {
var aRow = document.getElementById('txtRow' + i);
if (aRow.value.length <= 0) {
alert('Row ' + i + ' is empty');
return;
}
}
}
openInNewWindow(frm);
}
function deleteAll(obj){
var checked = document.getElementsByName(obj);
debugger
for(var i = 0; i < checked.length; i ++){
if(checked[i].checked){
var tr=checked[i].parentNode.parentNode;
var tbody=tr.parentNode;
tbody.removeChild(tr);
i--;
}
}
}
</script>
<!--Input Data-->
<form action="insert6.php" method="post" target="myframe">
Series:
<?php
function series(){
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT Series_NAME FROM series;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
echo("<option>".$row[$i]."</option>");
}
}
mysql_free_result($result);
}
?>
<select name="choose series">
<?php series(); ?>
</select><br>
<?php
function height(){
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT height FROM width_height GROUP BY height;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
echo("<option>".$row[$i]."</option>");
}
}
mysql_free_result($result);
}
?>
<p>Height(MM):
<select name="height" id="height0">
<?php height(); ?>
</select></p>
<?php
function width(){
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT width FROM width_height GROUP BY width;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
echo("<option>".$row[$i]."</option>");
}
}
mysql_free_result($result);
}
?>
<p>Width (MM):
<select name="width" id="width0">
<option><?php width(); ?></option>
</select><br>
<table border="1" id="tblSample">
<tr>
<td><input type="checkbox" id="op0" name="checkbox">
</td>
<td><input type="text" name="txtRow[]"
id="txtRow0" size="40"/></td>
<td>
<select name="selRow[]" id="selRow0">
<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
echo("<option>".$row[$i]."</option>");
}
}
mysql_free_result($result);
?>
</select>
</td>
</tr>
</table>
<input type="button" value="Add" onClick="addRowToTable();" />
<input type="button" name="delete_button" value="Delete" onClick="deleteAll('checkbox');" />
<input type="submit" name="submit" value="Submit" onclick="test();"/>
</form>
<script src="https://dl.dropboxusercontent.com/u/19096175/blog/selectDate/selectDate.js" type="text/javascript"></script>
Choose Date:<input onfocus="HS_setDate(this)" readonly="" type="text" value="Check" />
<br />
<hr/>
<iframe src="insert6.php" name="myframe" id="myframe" width="650" height="400" scrolling="no" frameborder="0">
</iframe>
</body>
</html>
This full code of the web site of the page.
insert6.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>DDD</title>
<style>
#tlist tr:last-child td {
background-color:#CCCCCC;
}
table{
table-layout: fixed;
}
th, td {
overflow: hidden;
}
#container
{
margin-left:auto;
margin-right:auto;
width:600px;
}
</style>
</head>
<body>
<?php
/*
$name = $_POST['selRow'];
$qty = $_POST['txtRow'];
foreach( $qty as $v ) {
print $v."<br>";
}
foreach( $name as $v ) {
print $v."<br>";
}
*/
?>
<script>
function delrecord(obj)
{
obj.parentNode.parentNode.parentNode.removeChild(obj.parentNode.parentNode);
var delbutton=document.getElementsByName("del");
var newzum=0;
for(var j=1;j <document.getElementsByName("del").length+1;j++)
{
newzum+=parseFloat(document.getElementById('total'+j).innerHTML);
}
znum.innerHTML =newzum;
}
function caltotal(e){
var fqty=document.getElementById('qty' +iteration);
var fprice=document.getElementById('price' + iteration);
var ftotal=document.getElementById('total'+ iteration);
var delbutton=document.getElementsByName("del");
ftotal.innerHTML= fqty.innerHTML * fprice.innerHTML;
newzum =0;
for(var j=1;j <=document.getElementsByName("del").length;j++)
{
newzum += parseFloat(document.getElementById('total'+j).innerHTML);
}
znum.innerHTML = newzum;
}
</script>
<div class="container">
<table width="450" border="0" cellspacing="1" cellpadding="0" class="tb" id="tlist">
<tr class="tit2">
<td>QTY </td>
<td>TILE </td>
<td>HEIGHT </td>
<td>WIDTH </td>
<td>PRICE </td>
<td>TOTAL </td>
<td>Action </td>
</tr>
<tr class="tit3">
<?php
if(isset($_POST["submit"])){
$t=count($_POST['selRow']);
$w=count($_POST['txtRow']);
for($i=0;$i<$t;$i++)
{
$qty[$i]= $_POST['txtRow'][$i];
$tile[$i]= $_POST['selRow'][$i];
$height = $_POST['height'];
$width = $_POST['width'];
echo "<tr class='tit3'><td>";
echo "".$qty[$i]."<br>";
echo "</td>";
echo "<td>";
echo "".$tile[$i]."<br>";
echo "</td>";
echo "<td>";
echo "".$height."<br>";
echo "</td>";
echo "<td>";
echo "".$width."<br>";
echo "</td>";
echo "<td>";
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
//foreach($_POST['selRow'] as $tile){
$query = "SELECT `Price` FROM `actualpanelmaterialsize` WHERE `Material ID` IN (SELECT `Material_ID` FROM `material` WHERE `Tile` = '".$tile[$i]."') AND `Width_Height ID` IN (SELECT `Width_Height ID` FROM `width_height` WHERE `Width` =".$_POST['width']." AND `Height` =".$_POST['height'].");";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
$price = $row[0];
echo $price."<br>";
}
//}
echo "</td>";
echo "<td id='total[$i]'>";
echo $total[$i]=$price*$qty[$i];
echo "</td>";
echo "<td>";
echo "<input type='button' value='Delete' name='del' onclick='delrecord(this);'>";
echo "</td>";
echo "</tr>";
}
echo "<script>";
echo "newzum =0;";
echo "for(var j=0;j <=document.getElementsByName('del').length+1;j++) {" ;
echo "for (var i=0;i<=document.getElementById('total['+i+']').innerHTML.length;i++){";
echo "newzum += parseFloat(document.getElementById('total['+i+']').innerHTML);";
echo "}";
echo "}";
echo "document.getElementById('znum').innerHTML = newzum;";
echo "</script>";
}
?>
</tr>
<tr class="tit3"> <td>Total </td> <td colspan=3> </td> <td colspan=2 align='right'> <b id="znum">0</b> </td> <td colspan=1> </td> </tr>
</table>
<script>
/*
for (var i=0;i<=document.getElementById("total["+i+"]").innerHTML.length;i++){
window.alert(document.getElementById("total["+i+"]").innerHTML);
}
*/
function Check(){
for (var i=0;i<=document.getElementById("total["+i+"]").innerHTML.length;i++){
window.alert(newzum);
}
}
</script>
<input type="button" value="Check" onClick="Check();"/>
</div>
</body>
</html>
Last, I was ask you guys about why znum.innerHTML cannot change the value.
Now, I put the javascript code inside the php language, the result still wrong...
My expected result:
Now I see the result:
After click the Check button to see newznum is correct but znum.innerHTML could not change this value
When pass the form to insert6.php, the total should be change the value.
Now, I cannot do it.
Anyone see the problem here?
Please you help me, I dun know where i get a mistake.
Thank you for reading my question!
I hope i will received the answer to help me to solve the problem
At first, Separation of logic is very important and what i see frmo your code is you are making DB calls from your view itself. Which shows poor way of coding. It will make it difficult to manager your code.
sel.options[0]= new Option("<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
if ($row[$i]=="FF")
echo($row[$i]);
}
}
mysql_free_result($result);
?>");
Now answer to your question:
echo "newzum =0;";
echo "for(var j=0;j <=document.getElementsByName('del').length+1;j++) {" ;
echo "for (var i=0;i<=document.getElementById('total['+i+']').innerHTML.length;i++){";
echo "newzum += parseFloat(document.getElementById('total['+i+']').innerHTML);";
echo "}";
echo "}";
echo "document.getElementById('znum').innerHTML = newzum;";
echo "</script>";
This lines of code will be executed before the page is loaded as its php.
as a result, when the page is rendered the script will not find document.getElementsByName('del') so it will throw undefined error.
To overcome this, Do those actions in onload function.
window.onload = function() {
// Inside this method put those lines. It will work.
}
Your code is too long, but I will try to answer from your title.
You must understand how php and javascript work. php is a server-side language, while javascript is a client side language. You can NOT execute php inside javascript. php does the processing on the server and then returns the results to the client. After this, the server is not aware of the client state.
In order to change the value of innerHTML, you can just use javascript. If you need to somehow interact with php, you should send AJAX calls to the server, where the php script can process and return new data.
The PHP will just echo the Javascript code, which is fine, but needlessly complex. You can just enter the Javascript code in the page.
The actual problem right now is this line:
document.getElementById('znum').innerHTML = newzum;
It is a line of Javascript in the global scope, and it will be executed as soon as the browser encounters it during the loading of the page.
But the element is should modify ('znum') is a couple of lines lower on the page:
<b id="znum">0</b>
That basically means that the element is not ready yet when the script is executed, so it cannot be found.
The solution is relatively simple: Execute the Javascript later (at the bottom) of the page, so it will execute when all relevant elements are already loaded.
Script errors like this result in an error or a warning which should be visible in the Console tab in the developer tools (F12) of your browser. So make sure you always look at that when debugging Javascript. It's really a tool you should master as a web developer. :)