I am working on a small project. It is a contacts database where users can add and search for contacts. So far you can add contacts and on page load a table populates with results. Great.
But I want to see if its possible to make each row clickable so that when the row is clicked the data is populated using javascript to the form.
One idea I am looking at is when the search results are pulled using a select statement, the id field is also selected and put in a hidden th. Then when the link is clicked the form uses a get method to select the data where the id = what has been selected. Would this work? or is there another way?
For brevity I did not use the include file that handles certain errors.
<!doctype html>
<html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="displayContacts">
<?php
//**********************************************
//*
//* Connect to MySQL and Database
//*
//**********************************************
$db = mysqli_connect('localhost','root','', 'test');
if (!$db)
{
print "<h1>Unable to Connect to MySQL</h1>";
}
include "0811_common_functions_mysqli.php";
$outputDisplay = "";
$myrowcount = 0;
//**********************************************
//*
//* SELECT from table and display Results
//*
//**********************************************
$sql_statement = "SELECT firstname, lastname, pcat, contact_id ";
//, congroup, cattype, company, position, email, website, phone, mphone, wphone, fax, add1, add2, city, state, zip, country, reference, entrydate, enteredby, notes ";
$sql_statement .= "FROM contacts ";
$sql_statement .= "ORDER BY lastname, firstname";
$sqlResults = selectResults($db, $sql_statement);
$error_or_rows = $sqlResults[0];
if (substr($error_or_rows, 0 , 5) == 'ERROR')
{
$outputDisplay .= "<br />Error on DB";
$outputDisplay .= $error_or_rows;
} else {
$arraySize = $error_or_rows;
$outputDisplay .= '<table id="resultstable" style="overflow-x:auto;">';
$outputDisplay .= '<tr><th>Last Name</th><th>First Name</th></tr>';
for ($i=1; $i <= $error_or_rows; $i++)
{
$myrowcount++;
$firstname = $sqlResults[$i]['firstname'];
$lastname = $sqlResults[$i]['lastname'];
$pcat = $sqlResults[$i]['pcat'];
$contactid = $sqlResults[$i]['contact_id'];
$outputDisplay .= "<tr>";
$outputDisplay .= "<td>".$firstname.' '.$lastname."</td>";
$outputDisplay .="<td>".$contactid."</td>";
$outputDisplay .= "<tr>";
$outputDisplay .="<td rowspan=1> $pcat</td>";
$outputDisplay .="</tr>";
$outputDisplay .= "</tr>";
}
$outputDisplay .= "</table>";
}
?>
<?php
$outputDisplay .= "<br /><br /><b>Number of Rows in Results: $myrowcount </b><br /><br />";
print $outputDisplay;
?>
</div>
<div id="main" class="main">
<form action="insert1.php" id="frmBox" method="post" onsubmit="return formSubmit();">
<table style="width:100%">
<tr>
<th>First Name: </th>
<th><input type='text' name='firstname' class="inp" size='20' /></th>
<th>Last Name: </th>
<th><input type='text' name='lastname' class="inp" size='20' /></th>
</tr>
<tr>
<th>Pages Category: </th>
<th><input type='text' name='pcat' class="inp" size='20' /></th>
<th>congroup: </th>
<th><input type='text' name='congroup' class="inp" size='20' /></th>
</tr>
<tr>
<th>Category Type:</th>
<th> <input type='text' name='cattype' class="inp" size='20' /></th>
<th>Company: </th>
<th><input type='text' name='company' class="inp" size='20' /></th>
</tr>
<tr>
<th>Position:</th>
<th><input type='text' name='position' class="inp" size='20' /></th>
</tr>
<tr>
<th>Email:</th>
<th><input type='text' name='email' class="inp" size='20' /> </th>
<th>Website: </th>
<th><input type='text' name='website' class="inp" size='20' /></th>
</tr>
<tr>
<th>H/D Phone: </th>
<th><input type='text' name='phone' class="inp" size='20' /></th>
<th>Mobile Phone: </th>
<th><input type='text' name='mphone' class="inp" size='20' /></th>
</tr>
<tr>
<th>Work Phone: </th>
<th><input type='text' name='wphone' class="inp" size='20' /> </th>
<th>Fax: </th>
<th><input type='text' name='fax' class="inp" size='20' /> </th>
</tr>
<tr>
<th>Address 1: </th>
<th><input type='text' name='add1' class="inp" size='50' /></th>
</tr>
<tr>
<th>Address 2:</th>
<th><input type='text' name='add2' class="inp" size='50' /></th>
</tr>
<tr>
<th>City: </th>
<th><input type='text' name='city' class="inp" size='20' /> </th>
<th>State:</th>
<th><input type='text' name='state' class="inp" size='20' /> </th>
</tr>
<tr>
<th>Zip/Postal Code:</th>
<th><input type='text' name='zip' class="inp" size='20' /></th>
<th>Country:</th>
<th><input type='text' name='country' class="inp" size='20' /></th>
</tr>
<tr>
<th>Reference:</th>
<th><input type='text' name='reference' class="inp" size='20' /></th>
<th>Date Added:</th>
<th> <input type='text' name='entrydate' class="inp" size='20' /></th>
</tr>
<tr>
<th>Entered By: </th>
<th> <input type='text' name='enteredby' class="inp" size='20' /></th>
</tr>
<tr>
<th>Notes:</th>
<th><textarea name="notes" row="10" class="inp" cols="20"></textarea></th>
</tr>
<tr>
<th><input type="submit" name="submit" class="sub-btn" value="Submit"></th>
</tr>
<h3 id="success"></h3>
</table>
</form>
</div>
<div id="results">
</div>
<script src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function formSubmit(){
$.ajax({
type:'POST',
url:'insert1.php',
data:$('#frmBox').serialize(),
success:function(response){
$('#success').html(response);
}
});
var form=document.getElementById('frmBox').reset();
return false;
}
function addRowHandlers() {
var table = document.getElementById("resultstable");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[1];
var id = cell.innerHTML;
alert("id:" +id);
function formPopulate(id){
$.ajax({
url: "result.php",
success: (function(result){
$("results").html(result);
})
})
}
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
window.onload = addRowHandlers();
</script>
</body>
</html>
Results.php
<!doctype html>
<html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="displayContacts">
<?php
//**********************************************
//*
//* Connect to MySQL and Database
//*
//**********************************************
$db = mysqli_connect('localhost','root','', 'test');
if (!$db)
{
print "<h1>Unable to Connect to MySQL</h1>";
}
include "0811_common_functions_mysqli.php";
$outputDisplay = "";
$myrowcount = 0;
//**********************************************
//*
//* SELECT from table and display Results
//*
//**********************************************
$sql_statement = "SELECT firstname, lastname, pcat, contact_id ";
//, congroup, cattype, company, position, email, website, phone, mphone, wphone, fax, add1, add2, city, state, zip, country, reference, entrydate, enteredby, notes ";
$sql_statement .= "FROM contacts ";
$sql_statement .= "ORDER BY lastname, firstname";
$sqlResults = selectResults($db, $sql_statement);
$error_or_rows = $sqlResults[0];
if (substr($error_or_rows, 0 , 5) == 'ERROR')
{
$outputDisplay .= "<br />Error on DB";
$outputDisplay .= $error_or_rows;
} else {
$arraySize = $error_or_rows;
$outputDisplay .= '<table id="result" style="overflow-x:auto;">';
for ($i=1; $i <= $error_or_rows; $i++)
{
$myrowcount++;
$firstname = test_get($sqlResults[$i]['firstname']);
$lastname = test_get($sqlResults[$i]['lastname']);
$pcat = test_get($sqlResults[$i]['pcat']);
$contactid = $sqlResults[$i]['contact_id'];
$outputDisplay .= "<tr>";
$outputDisplay .= "<td>".$firstname.' '.$lastname."</td>";
$outputDisplay .="<td>".$contactid."</td>";
$outputDisplay .= "<tr>";
$outputDisplay .="<td rowspan=1> $pcat</td>";
$outputDisplay .="</tr>";
$outputDisplay .= "</tr>";
}
$outputDisplay .= "</table>";
mysqli_close($conn);
}
function test_get($data){
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
?>
</div>
</body>
</html>
insert.php
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$servername = "localhost";
$username= "root";
$dbpassword = "";
$dbname="test";
$conn=mysqli_connect($servername, $username, $dbpassword, $dbname);
if(!$conn){
die("could not connect:".mysqli_connect_error());
} else{
$firstname=test_input($_POST['firstname']);
$lastname=test_input($_POST['lastname']);
$pcat=test_input($_POST['pcat']);
$congroup=test_input($_POST['congroup']);
$cattype=test_input($_POST['cattype']);
$company=test_input($_POST['company']);
$position=test_input($_POST['position']);
$email=test_input($_POST['email']);
$website=test_input($_POST['website']);
$phone= test_input($_POST['phone']);
$mphone=test_input($_POST['mphone']);
$wphone=test_input($_POST['wphone']);
$fax=test_input($_POST['fax']);
$add1=test_input($_POST['add1']);
$add2=test_input($_POST['add2']);
$city=test_input($_POST['city']);
$state=test_input($_POST['state']);
$zip=test_input($_POST['zip']);
$country=test_input($_POST['country']);
$reference=test_input($_POST['reference']);
$entrydate=test_input($_POST['entrydate']);
$enteredby=test_input($_POST['enteredby']);
$notes=test_input($_POST['notes']);
$sql="INSERT INTO contacts(firstname, lastname, pcat, congroup, cattype, company, position, email, website, phone, mphone, wphone, fax, add1, add2, city, state, zip, country, reference, entrydate, enteredby, notes) ";
$sql .= "values (";
$sql .= "'".$firstname."', '".$lastname."', '".$pcat."', '".$congroup."', '".$cattype."', '".$company."', '".$position."', '".$email."', '".$website."', '".$phone."', '".$mphone."', '".$wphone."', '".$fax."', '".$add1."', '".$add2."', '".$city."', '".$state."', '".$zip."', '".$country."', '".$reference."', '".$entrydate."', '".$enteredby."', '".$notes."'";
$sql .= ")";
if(mysqli_query($conn, $sql)){
echo "Record Inserted";
}else{
echo "insert failed";
}
mysqli_close($conn);
}
function test_input($data){
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
For the table tr you call a onclick funtion and send an id through it
<tr onClick="formPopulate(id)" >
And when the funtion trigger call a ajax call to retrieve the data and the append to form
in javascript
function formPopulate(id) {
//send an ajax call here to get the data without reloading the page
//after ajax call append the values of ajax response to the form
}
Related
I've been having issues trying to call a php script via javascript when the user changes a value in the "Assigned To Group" selection. Which is ultimately supposed to change the option list of, a not yet created, "Assign to User" selection.
I keep getting an error saying that it doesn't recognize the function's name. When I tried running a simple value change and alert to verify it could get the values, it recognized it and it updated accordingly. When I added the Ajax command is when it started not recognizing it. I'm sure I'm probably just using incorrectly, somehow, sense I've never used ajax before. But from the samples I've seen, it seems fairly straight forward.
Error: Uncaught ReferenceError: onChangeAssignedGroup is not defined at HTMLSelectElement.onchange
<?php
include('classes/class.User.php');
include('classes/class.Role.php');
include('classes/class.User_Role.php');
include('constants.php');
session_start();
?>
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function onChangeAssignedGroup() {
var new_assigned_to_role_id = document.getElementById("option_list_assigned_to_role_id").value;
document.getElementById("assignedGroupId").innerHTML = "You selected: " + new_assigned_to_role_id;
alert(new_assigned_to_role_id);
$.ajax({
method: "POST",
url: "ticket_details.php",
data:{
ticket_id:$_POST['ticket_id'];
creator_user_id:$_POST['creator_user_id'];
creator_user_name:$_POST['creator_user_name'];
status:$_POST['status'];
priority:$_POST['priority'];
title:$_POST['title'];
assigned_to_role_id:new_assigned_to_role_id;
assigned_to_role_name:"";
assigned_to_user_id:$_POST['assigned_to_user_id'];
assigned_to_user_name:$_POST['assigned_to_user_name'];
},
success: function () {
alert('form was submitted');
}
});
}
</script>
</head>
<body>
<p>Return to Tickets</p>
<?php
if(isset($_POST['submit']) or isset($_POST['submit_new_comment']) or isset($_POST['submit_update_ticket'])){
$ticket_id = $_POST['ticket_id'];
$creator_user_id = $_POST['creator_user_id'];
$creator_user_name = $_POST['creator_user_name'];
$status = $_POST['status'];
$priority = $_POST['priority'];
$title = $_POST['title'];
$assigned_to_role_id = $_POST['assigned_to_role_id'];
$assigned_to_role_name = $_POST['assigned_to_role_name'];
$assigned_to_user_id = $_POST['assigned_to_user_id'];
$assigned_to_user_name = $_POST['assigned_to_user_name'];
//connect to database
include("database_connection.php");
//handle update to ticket
if(isset($_POST['submit_update_ticket'])){
$update = $mysqli->query("UPDATE `ticket` SET `status` = '$status', `priority` = '$priority',
`assigned_to_role_id` = '$assigned_to_role_id', `assigned_to_role_name` = '$assigned_to_role_name',
`assigned_to_user_id` = '$assigned_to_user_id', `assigned_to_user_name` = '$assigned_to_user_name'
WHERE `ticket`.`id` = $ticket_id");
if(!$update){
echo"<p>".$mysqli->error."</p>";
}
}
//handle new comment
if(isset($_POST['submit_new_comment'])){
$new_comment = $_POST['new_comment'];
$current_id = $_SESSION['user']->getId();
$current_username = $_SESSION['user']->getUsername();
//sanitize data
$new_comment = $mysqli->real_escape_string($new_comment);
unset($_POST['submit_new_comment']);
//insert new comment into database.
$insert = $mysqli->query("INSERT INTO ticket_comment (ticket_id, user_id, user_name, text) VALUES ('$ticket_id', '$current_id', '$current_username', '$new_comment')");
if(!$insert){
echo"<p>".$mysqli->error."</p>";
}
}
//include arrays for converting values returned
include("value_maps.php");
echo "<p id='assignedGroupId'></p>";
echo "<p>role id:".$assigned_to_role_id."</p>";
echo "<p>role name:".$assigned_to_role_name."</p>";
if(in_array($assigned_to_role_id,$_SESSION['user']->getRoles())){
echo "<p>you have this role.</p>";
} else {
echo "<p>you don't have this role.</p>";
}
print_r($_SESSION['user']->getRoles());
echo"
<form action='' method='post'>
<input type='hidden' name='ticket_id' value='$ticket_id'>
<input type='hidden' name='creator_user_id' value='$creator_user_id'>
<input type='hidden' name='creator_user_name' value='$creator_user_name'>
<input type='hidden' name='title' value='$title'>
<input type='hidden' name='assigned_to_role_id' value='$assigned_to_role_id'>
<input type='hidden' name='assigned_to_role_name' value='$assigned_to_role_name'>
<input type='hidden' name='assigned_to_user_id' value='$assigned_to_user_id'>
<input type='hidden' name='assigned_to_user_name' value='$assigned_to_user_name'>
<table border='0' align='center' cellpadding='5'>
<tr>
<th>Ticket ID</th>
<th>Title</th>
<th>Status</th>
<th>Priority</th>
<th>Assigned To Group</th>
<th>Assigned To User</th>
</tr>
<tr>
<td>$ticket_id</td>
<td>$title</td>";
if(in_array($assigned_to_role_id,$_SESSION['user']->getRoles()) or in_array(ROLE_ID_ADMIN,$_SESSION['user']->getRoles())){
echo "<td><select name='status'>";
$status_index = 0;
foreach($status_array as $status_choice){
if($status == $status_index){
echo "<option value='". $status_index."' selected>". $status_choice ."</option>";
} else {
echo "<option value='". $status_index."'>". $status_choice ."</option>";
}
$status_index++;
}
echo "</select></th>";
echo "<td><select name='priority'>";
$priority_index = 0;
foreach($priority_array as $priority_choice){
if($priority == $priority_index){
echo "<option value='". $priority_index."' selected>". $priority_choice ."</option>";
} else {
echo "<option value='". $priority_index."'>". $priority_choice ."</option>";
}
$priority_index++;
}
echo "</select></th>";
} else {
echo "<td>".$status_array[$status]."</th>";
echo "<td>".$priority_array[$priority]."</th>";
}
if(in_array(ROLE_ID_ADMIN,$_SESSION['user']->getRoles())){
echo "<td><select id='option_list_assigned_to_role_id' name='assigned_to_role' onchange='onChangeAssignedGroup()'>";
foreach($_SESSION['roles'] as $assigned_to_role_choice){
if($assigned_to_role_id == $assigned_to_role_choice->getId()){
echo "<option value='". $assigned_to_role_choice->getId()."' selected>". $assigned_to_role_choice->getName() ."</option>";
} else {
echo "<option value='". $assigned_to_role_choice->getId()."'>". $assigned_to_role_choice->getName() ."</option>";
}
}
echo "</select></td>";
} else {
echo "<td>$assigned_to_role_name</td>";
echo "<td>$assigned_to_user_name</td>";
}
echo"
</tr>
<tr>
<td colspan='5'></td>
<td><input type='submit' name='submit_update_ticket' value='Update Ticket Details' required></td>
</tr>
</table>
</form>
";
//get back ticket details
$results = $mysqli->query("SELECT `id`,`ticket_id`,`user_id`,`user_name`,`text`,`create_date`,`modify_date` FROM `ticket_comment` WHERE `ticket_id` = ".$ticket_id." ORDER BY `create_date`");
//if insert was successful
if($results){
//header('location:registration_email_sent.php');
if ($results->num_rows > 0){
echo "
<table border='0' align='center' cellpadding='5'>
<tr>
<th>Username</th>
<th>Comment</th>
</tr>
";
while($row = $results->fetch_row()){
echo"
<tr>
<td>".$row[3].": </td>
<td>".$row[4]."</td>
</tr>";
}
} else {
echo "<p>No comments found. </p>";
}
}
$mysqli->close();
echo"
<form method='post' action=''>
<input type='hidden' name='ticket_id' value='$ticket_id'>
<input type='hidden' name='creator_user_id' value='$creator_user_id'>
<input type='hidden' name='creator_user_name' value='$creator_user_name'>
<input type='hidden' name='status' value='$status'>
<input type='hidden' name='priority' value='$priority'>
<input type='hidden' name='title' value='$title'>
<input type='hidden' name='assigned_to_role_id' value='$assigned_to_role_id'>
<input type='hidden' name='assigned_to_role_name' value='$assigned_to_role_name'>
<input type='hidden' name='assigned_to_user_id' value='$assigned_to_user_id'>
<input type='hidden' name='assigned_to_user_name' value='$assigned_to_user_name'>
<table border='0' align='center' cellpadding='5'>
<tr>
<th>New Comment</th>
<th><input type='submit' name='submit_new_comment' value='Post New Comment'></th>
</tr>
<tr>
<td colspan='2'><textarea name='new_comment' rows='10' cols='30' placeholder='New Comment Here' required></textarea></td>
</tr>
</table>
</form>
";
}
?>
</body>
</html>
In the data object in your ajax request, you need to replace the semicolons with commas.
You should also always use prepared statements to interact with the database.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I've got some code where I have to input my contact data from client, and output data from MySQL database which creates new rows in table
Also there's additional function which has to be inside the code - but I've no idea how to handle this problem. I have to count the amount of element pieces x their weight in real-time to show the client the total weight the order is going to have.
The problem is I don't know how to make the client see it whenever they change the value of Pieces in <input>.
Lastly, the data from the form and table has to be sent to employee via email.
PHP Code:
<html>
<head>
<meta charset="utf-8" />
<meta name="calculator" content="width=device-width, initial-scale=1"/>
<title>Test</title>
<link rel="stylesheet" href="style.css" >
</head>
<body>
<!-- including calc.php file which contains all variables -->
<?php include 'calc.php'; ?>
<!-- Printing the form -->
<form method="post" action="sendform.php"><br>
<center>
<h1>TEST</h1>
<input id="Name" type="text" placeholder="<?= $form['FIRMA']; ?>" class="form-contact" required><br>
<input id="Adres" type="text" placeholder="<?= $form['ADRES']; ?>" class="form-contact" required><br>
<input id="Email" type="email" placeholder="<?= $form['EMAIL']; ?>" class="form-contact" required><br>
<input id="Country" type="text" placeholder="<?= $form['COUNTRY']; ?>" class="form-contact" value="" size="1" pattern="[0-9]{2}" maxlength="2" required>
<input id="Phone" type="text" placeholder="<?= $form['PHONE']; ?>" class="form-contact" pattern="[0-9]{9}" maxlength="9" required>
<br>
<!-- Printing out the table -->
<table class="table-responsive" border="1">
<thead>
<tr>
<th><?= $form['PRODUCTS']; ?></th>
<th><?= $form['CATALOG']; ?></th>
<th><?= $form['DESC']; ?></th>
<th><?= $form['WEIGHT']; ?></th>
<th><?= $form['TWEIGHT']; ?></th>
<br>
</tr>
</thead>
<tbody>
<?php
# Database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "data";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
#echo "Connection successfull!";
# Questions for Database
$sql = 'SELECT * FROM `elements`';
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
//output data each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".'<input class="pcs-input" min=0 maxlength="3" value=0 size="2px" style="background-color: white;" name="inputs[]">';
echo "</td><td>Nr. " . $row["pcode"] . "</td><td> " . $row["fullname"]. "</td><td> " . $row["weight"] . "kg</td><td><div id='sumWeight'></div></td></tr>";
}
} else {
echo "0 Results";
}
mysqli_close($connection);
?>
</tbody>
</table>
<!-- Counting all needed atributes -->
<div id="totalWeight">totalWeight</div>
<!-- Submit btn -->
<br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
</center>
</form>
</body>
</html>
JavaScript Code
<script type="text/javascript">
document.addEventListener(function()
input.OnChange = calculateForm();
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function () {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
} else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
totalWeight += sumWeight;
}
});
document.write(totalWeight.toFixed(2) + ' kg');
}
)};
</script>
Updated
Well it doesn't work again, no errors, just doesn't multiply
I think the problem might be with transporting data from table/database into the variable, any solution?
<?php
# Database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "data";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
#echo "Connection successfull!";
# Questions for Database
$sql = 'SELECT * FROM `elements`';
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
//output data each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>"."<input type='number' class='pcs-input' id='inputs' data-weight=".$row["weight"];
echo "></input>";
# echo "<tr><td>".$row["id"].'';
echo "</td><td>Nr. " . $row["pcode"] . "</td><td> " . $row["fullname"]. "</td><td> " . $row["weight"] . "kg</td><td><div id='sum-Weight2'></div></td></tr>";
}
} else {
echo "0 Results";
}
#Declaring JavaScript Code inside PHP
mysqli_close($connection);
?>
</tbody>
</table>
<script type="text/javascript">
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function () {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
} else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
$(this).parent().parent().find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
totalWeight += sumWeight;
};
$('.totalGewicht').html(totalWeight.toFixed(2) + ' kg');
}
)};
</script>
<!-- Counting all needed atributes -->
<div id="totalWeight"></div>
<!-- Submit btn -->
<br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
</center>
</form>
Overall there are quite a few issues with your code, which can be summarised as problems with
invalid HTML (e.g. duplicate IDs, incorrectly written input element, un-closed table rows, un-closed data attributes)
over-complicated HTML
typing or case errors (e.g. W instead of w)
incorrect CSS selectors in the JavaScript
lack of initial default data (e.g. if there are no numbers in any one of the input boxes, the calculation will fail because trying to add a blank value to another number results in NaN (Not a Number)
calculation did not run when page loads, so data is missing until the user changes something (which is no use, if they want to see the current weight before changing any values)
This client-side demo demonstrates the HTML you need to get your PHP to produce, and the correct JavaScript / jQuery code in order to do the calculations and display the results:
$(function() {
$(".pcs-input").change(calculateForm); //set up the event handler
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function() {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
}
else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
$(this).closest("tr").find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
totalWeight += sumWeight;
};
$('#totalWeight').html(totalWeight.toFixed(2) + ' kg');
})
};
calculateForm(); //call it once when the page first loads too, to set up the initial data
});
table
{
border-collapse:collapse;
}
td
{
border: solid 1px black;
padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td><input type='number' class='pcs-input' data-weight='3' value='1' /></td>
<td>Nr. 14536</td>
<td>Test 1</td>
<td>3 kg</td>
<td class='sum-weight2'></td>
</tr>
<tr>
<td><input type='number' class='pcs-input' data-weight='15' value='1' /></td>
<td>Nr. 23431</td>
<td>Test 2</td>
<td>15 kg</td>
<td class='sum-weight2'></td>
</tr>
<tr>
<td><input type='number' class='pcs-input' data-weight='4' value='1' /></td>
<td>Nr. 33125</td>
<td>Test 3</td>
<td>4 kg</td>
<td class='sum-weight2'></td>
</tr>
</tbody>
</table>
Total Weight: <span id="totalWeight"></span>
Remember you need to move the focus from the textbox to another element (using mouse or tab key) before the "change" event will fire. (It will also run if you use the up/down buttons on the input box.)
So this means, as well as editing the JavaScript as I've shown, you need to alter the PHP so it outputs the HTML table rows with the structure and data I've demonstrated above.
This should work:
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>"."<input type='number' class='pcs-input' data-weight='".$row["weight"]."' value='1' /></td>";
echo "<td>Nr. ".$row["pcode"]."</td><td>".$row["fullname"]."</td><td>".$row["weight"]."kg</td><td class='sum-weight2'></td></tr>";
}
Resolution:
<body>
<!-- including calc.php file which contains all variables -->
<?php include 'calc.php'; ?>
<!-- Printing the form -->
<form method="post" action="sendform.php"><br>
<center>
<input id="Name" type="text" placeholder="<?= $form['FIRMA']; ?>" class="form-contact" required><br>
<input id="Adres" type="text" placeholder="<?= $form['ADRES']; ?>" class="form-contact" required><br>
<input id="Email" type="email" placeholder="Email" class="form-contact" required><br>
<input id="Country" type="text" placeholder="49" class="form-contact" value="" size="1" pattern="[0-9]{2}" maxlength="2" required>
<input id="Phone" type="text" placeholder="Tel" class="form-contact" pattern="[0-9]{9}" maxlength="9" required>
<br>
<!-- Printing out the table -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class=".table-responsive">
<thead>
<tr>
<th><?= $form['PRODUCTS']; ?></th>
<th><?= $form['CATALOG']; ?></th>
<th><?= $form['DESC']; ?></th>
<th><?= $form['WEIGHT']; ?></th>
<th><?= $form['TWEIGHT']; ?></th>
<br>
</tr>
</thead>
<tbody>
<?php
# Database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "data";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
#echo "Connection successfull!";
# Questions for Database
$sql = 'SELECT * FROM `elements`';
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
//output data each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>"."<input type='number' class='pcs-input' data-weight='".$row["weight"]."' value='0' min='0' /></td>";
echo "<td>Nr. ".$row["pcode"]."</td><td>".$row["fullname"]."</td><td>".$row["weight"]."kg</td><td class='sum-weight2'></td></tr>";
}
} else {
echo "0 Results";
}
#Declaring JavaScript Code inside PHP
mysqli_close($connection);
?>
</tbody>
</table>
<script type="text/javascript">
$(function() {
$(".pcs-input").change(calculateForm); //set up the event handler
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function() {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
}
else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
$(this).closest("tr").find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
totalWeight += sumWeight;
};
$('#totalWeight').html(totalWeight.toFixed(2) + ' kg');
})
};
calculateForm(); //call it once when the page first loads too, to set up the initial data
});
</script>
<!-- Counting all needed atributes -->
Total Weight: <span id="totalWeight"></span>
<!-- Submit btn -->
<br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
</center>
</form>
</body>
FYI- I am making a timesheet project using PHP and MySQL
I am new to PHP, I tried to use PHP make HTML table rows and assign them row id, but the problem is that my table is displaying a large number of rows, so I made a javascript filter to display only rows which match with the filter values
But the problem is I don't how to use row id and then use their values to get compared with the javascript variable and based on match its CSS property is set to display (if matched) or hide (if not matched).
Is there any other way to do this?
Here is Filter Section.
<div class='row'>
<div class='col'>
<label>Select Filters:</label>
</div>
</div>
<div class='row'>
<div class='col'>
<div class='filter'>
<label>EmpID:</label>
<select id='empid_select'>
<option value='' >select</option>
<?php
include('connection.php');
$stmt = $conn->prepare('SELECT `EmpID`, `Name` FROM `employee_data` ORDER BY `EmpID` ');
if($stmt->execute()){
$stmt->bind_result($empid, $empname);
while($stmt->fetch()){
echo "<option value='$empid'>$empid - $empname</option>";
}
}else{
printf("Error: %s\n", $conn->error);
}
$stmt->close();
?>
</select>
<label>Project Code:</label>
<select id='projectcode_select'>
<option value=''>Select</option>
<?php
include('connection.php');
$stmt = $conn->prepare('SELECT `Projectcode`, `Title` FROM `Projectcodetbl` ORDER BY `Projectcode` ASC ');
if($stmt->execute()){
$stmt->bind_result($projectcode, $title);
while($stmt->fetch()){
echo "<option value='$projectcode'>$projectcode - $title</option>";
}
}else{
printf("Error: %s\n", $conn->error);
}
?>
</select>
<label>Start Date: </label>
<input type='date' name='startdate-filter' id='startdate-filter' >
<label>End Date: </label>
<input type='date' name='enddate-filter' id='enddate-filter' >
<button name='notseen-entries-filter-button' id='notseen-entries-filter-button'>Apply</button>
</div>
</div>
</div>
Here is my script to get value form the filter section.
<script>
$(document).ready(function(){
$('[name="notseen-entries-filter-button"]').click(function(e){
var empid = $('#empid_select option:selected').val();
var projectcode = $('#projectcode_select option:selected').val();
var startdate = $('#startdate-filter').val();
var enddate = $('#enddate-filter').val();
alert("Filter rows with values EmpID: "+empid+", ProjectCode: "+projectcode+", StartDate: "+startdate+", EndDate: "+enddate);
});
});
</script>
PHP Function for displaying the table heading
function displayTableHeading(){
echo "
<form action='selected.php' method='post'>
<table border='1' cellpadding='10' cellspacing='0'>
<tr>
<th colspan='13'><button type='submit' class='btn btn-outline-primary' style='border-radius: 3px;'><i class='fas fa-edit' style='margin-right:10px;'></i>Update</button>
</tr>
<tr>
<th>Row</th>
<th>EmpID - Name</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Hrs</th>
<th>Project Code</th>
<th>Task Performed</th>
<th>Invoice Num</th>
<th colspan=3>Status</th>
</tr>";
}
PHP Function for displaying the table rows.
//Webpage Table Row
function displayTableRow($row, $i, $empid){
$notBillable = intval( $row['Status'] )==1 ? 'checked' : '';
$billablePlusNotInvoiced = intval( $row['Status'] )==2 ? 'checked' : '';
$billablePlusInvoiced = intval( $row['Status'] )==3 ? 'checked' : '';
printf("
<!-- record: %d -->
<tr id='%d'>
<td><input type='text' size='1' value='%d' ></td>
<td><input type='text' size='10' name='empid[]' value='%s'></td>
<td><input type='text' size='7' name='date[]' value='%s' ></td>
<td><input type='text' size='5' name='stime[]' value='%s' ></td>
<td><input type='text' size='5' name='etime[]' value='%s' ></td>
<td><input type='text' size='1' name='hours[]' value='%s' ></td>
<td><b><input type='text' size='9' name='projectcode[]' value='%s' ></b></td>
<td><input type='text' size='30' name='taskperformed[]' value='%s' ></td>
<td><input type='text' size='8' name='invoicenum[]' value='%s' ></td>
<td><input type='radio' name='status_{$i}[]' value='1' %s/>NB</td>
<td><input type='radio' name='status_{$i}[]' value='2' %s/>B+NI</td>
<td><input type='radio' name='status_{$i}[]' value='3' %s/>B+I</td>
<input type='hidden' name='modifieddate[]' value='%s'>
</tr>",
$i,$i,$i,
getEmpNameById($empid),
$row['Date'],
$row['StartTime'],
$row['EndTime'],
$row['NoOfHours'],
$row['ProjectCode'],
$row['TaskPerformed'],
$row['InvoiceNumber'],
$notBillable,
$billablePlusNotInvoiced,
$billablePlusInvoiced,
$row['ModifiedDate']
);
}
PHP code for calling above function and displaying the HTML table.
$sumNoOfHours = 0.0;
displayTableHeading();
$i=1;
foreach($empid_array as $code){
//split the $code variable to get the emp id
$codearr = explode(" - ", $code);
$empid = $codearr[0];
$selectSql = "SELECT * FROM `mastertbl` WHERE EmpID = '$empid' AND Status = 0 ORDER BY Date DESC, ModifiedDate DESC";
$result = mysqli_query($conn, $selectSql) or die( mysqli_error($conn));
while($row = mysqli_fetch_array($result))
{
$sumNoOfHours = $sumNoOfHours + $row['NoOfHours'];
displayTableRow($row, $i, $empid);
$i++;
}
}
I have text field inside the table, and also the data below in it..I want to display the data to text field after clicking the row.
I tried these code but nothing happens. Help me please.
These are the code for the table.
<table id="tableqwe">
<tr>
<th>Name</th>
<th>Id Number</th>
<th>Course</th>
<th>Year level</th>
<th>School Year</th>
<th>Semester</th>
<th></th>
</tr>
<tr>
<th><input type="Text" id="name1" name="name1" style="width:200px;"></th>
<th><input type="Text" id="idnumber2" name="idnumber2" style="width:200px;"></th>
<th><input type="Text" id="course3" name="course3" style="width:80px;"></th>
<th><input type="Text" id="yearlvl4" name="yearlvl4" style="width:200px;"></th>
<th><input type="Text" id="schoolyear5" name="schoolyear5" style="width:150px;"></th>
<th><input type="Text" id="semester6" name="semester6" style="width:100px;"></th>
<th><input type="button" value="Add" class="btntable edit" style="width:50px;"></th>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['Id_number'] . "</td>";
echo "<td>" . $row['course'] . "</td>";
echo "<td>" . $row['year_level'] . "</td>";
echo "<td>" . $row['school_year'] . "</td>";
echo "<td>" . $row['semester'] . "</td>";
echo "<td>"?><input type="button" class="btntable delete" value="Delete" style="width:50px;"><?php
echo "</tr>";
}
?>
</table>
And these are the javascript code...
<script>
var table1 = document.getElementById('tableqwe');
for(var i = 2; i < table1.rows.length; i++)
{
table.rows[i].onclick = function()
{
rIndex = this.rowIndex;
console.log(rIndex);
document.getElementsByName("name1").value = this.cells[0].innerHTML;
document.getElementsByName("idnumber2").value = this.cells[1].innerHTML;
document.getElementsByName("course3").value = this.cells[2].innerHTML;
document.getElementsByName("yearlvl4").value = this.cells[3].innerHTML;
document.getElementsByName("schoolyear5").value = this.cells[4].innerHTML;
document.getElementsByName("semester6").value = this.cells[5].innerHTML;
}
}
</script>
Can someone help me with this.! All I want is if I click any row of the table, it will directly display it to the text field.
You should use HTML DOM getElementById() Method to get the element with the specified ID.
HTML DOM getElementsByName() Method Get all elements with the specified name.
You have to edit your js script as follows.
If you are using 'HTML DOM getElementsByName() Method' to assign value to that specific element you should use it as document.getElementsByName("name1")[0].value="value". Since this method returns the collection of objects having the same name passed as it's parameter.
If you are using the HTML DOM getElementById() you can assign values into it by using the code as document.getElementById("idofelement").value="value".
An example is given in the snippet below.
var table1 = document.getElementById('tableqwe');
for(var i = 2; i < table1.rows.length; i++)
{
table1.rows[i].onclick = function()
{
rIndex = this.rowIndex;
console.log(this.cells[0].innerHTML);
document.getElementById("name1").value = this.cells[0].innerHTML;
console.log(document.getElementsByName("name1")[0].value);
document.getElementById("idnumber2").value = this.cells[1].innerHTML;
document.getElementById("course3").value = this.cells[2].innerHTML;
document.getElementById("yearlvl4").value = this.cells[3].innerHTML;
document.getElementById("schoolyear5").value = this.cells[4].innerHTML;
document.getElementById("semester6").value = this.cells[5].innerHTML;
}
}
<table id="tableqwe">
<tr>
<th>Name</th>
<th>Id Number</th>
<th>Course</th>
<th>Year level</th>
<th>School Year</th>
<th>Semester</th>
<th></th>
</tr>
<tr>
<th><input type="Text" id="name1" name="name1" style="width:200px;"></th>
<th><input type="Text" id="idnumber2" name="idnumber2" style="width:200px;"></th>
<th><input type="Text" id="course3" name="course3" style="width:80px;"></th>
<th><input type="Text" id="yearlvl4" name="yearlvl4" style="width:200px;"></th>
<th><input type="Text" id="schoolyear5" name="schoolyear5" style="width:150px;"></th>
<th><input type="Text" id="semester6" name="semester6" style="width:100px;"></th>
<th><input type="button" value="Add" class="btntable edit" style="width:50px;"></th>
</tr>
<tr>
<td>name</td>
<td>12</td>
<td>Course</td>
<td>Course 12</td>
<td>School year 12</td>
<td>School year 12</td>
<td><input type="button" class="btntable delete" value="Delete" style="width:50px;"></tr>;
</table>
Change the code like this.
<?php
while($row = mysqli_fetch_array($result)) {
echo "<tr contenteditable = 'true' id='name' data-name= '//php variable like $id '>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>"?><input type="button" class="btntable delete" value="Delete" style="width:50px;"><?php
echo "</tr>";
}
?>
then change your javascript to like this (Im coding it Jquery and change it you want.)
<Script>
$(document).on('click', '#button Id or Class here', function(){
//get id of user updates
var id = $(this).data("name");
// get values
var val = $(this).text();
});
</script>
this the solution. if is this help for your leave a comment.
I have the following 2 php scripts. booking.php is created on the fly doing a call to a mysql database and returning results into the tables. To make this a somewhat simple example and only am showing a few fields...actually table has 54 fields in them.
The idea behind this is every table is a Customer order. The openbutton or closebutton is a image representing what status the order is in. If it is closed the closedbutton image appears. If the order is opened then the openbutton image appears. when I click on the
Everything work (process wise), however, the image only allows me to click it once per table and requires me to refresh the page to click on it again.
What is want is to be able to click the openbutton/closedbutton image on a table as many times as I want and have the correct image appear after I click it and the mysql table has processed it.
booking.php
<?php
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.status_button').click(function(){
var element = $(this);
var I = element.attr('id');
var id=$('#id'+I).val();
var sname = $(this).attr('title');
$.post('openclose.php', {id: id, sname: sname},
function(data){
var response = (data).split(';',2);
$('#messageA'+I).html(response[0]);
$('#messageA'+I).hide();
$('#messageA'+I).fadeIn(1500);
$('#messageB'+I).html(response[1]);
$('#messageB'+I).hide();
$('#messageB'+I).fadeIn(1500);
});
return false
;})
;});
</script>
<style type='text/css'>
table {border: 1px solid black}
td, tr {border: 0}
</style>
</head>
<body>
<table>
<th>Id</th>
<th>Year</th>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
<tr>
<td><input type='text' id='id1' size='3' readonly='readonly' value='1'></td>
<td><input type='text' id='year1' size='2' value='2013'></td>
<td><input type='text' id='fname1' size='10' value='Brian'></td>
<td><input type='text' id='lname1' size='15'value='Smith'></td>
<td><div id='messageB1'><a id='1', href='#' class = 'status_button' title='Close1'> </div>
<div id='messageA1'><img src='images/openbutton.jpg', title='Order Status' border='0' height='24' width='24'></img></div></a></td>
</tr>
</table>
<table>
<th>Id</th>
<th>Year</th>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
<tr>
<td><input type='text' id='id2' size='3' readonly='readonly' value='2'></td>
<td><input type='text' id='year2' size='2' value='2014'></td>
<td><input type='text' id='fname2' size='10' value='Kurt'></td>
<td><input type='text' id='lname2' size='15'value='Jones'></td>
<td><div id='messageB2'><a id='2', href='#' class = 'status_button' title='Open2'> </div>
<div id='messageA2'><img src='images/closebutton.jpg', title='Order Status' border='0' height='24' width='24'></img></div></a></td>
</tr>
</table>
<table>
<th>Id</th>
<th>Year</th>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
<tr>
<td><input type='text' id='id3' size='3' readonly='readonly' value='2'></td>
<td><input type='text' id='year3' size='2' value='2014'></td>
<td><input type='text' id='fname3' size='10' value='Ryan'></td>
<td><input type='text' id='lname3' size='15'value='Davis'></td>
<td><div id='messageB3'><a id='3', href='#' class = 'status_button' title='Open3'></div>
<div id='messageA3'><img src='images/openbutton.jpg', title='Order Status' border='0' height='24' width='24'></img></div></a></td>
</tr>
</table>
</body>
?>
openclose.php
<?php
include('connection.php');
$id=$_POST['id'];
$sname=$_POST['sname'];
$rest = substr($sname, 0, -1);
if ($rest == "Open")
$change="O";
else
$change="C";
$query = "UPDATE info SET status_ = '$change' WHERE id = $id";
$result = mysql_query($query) or die ( mysql_error ());
if ($change == "O")
$image ="<img src='images/openbutton.jpg', title='Order Status' border='0' height='24' width='24'></img>";
else
$image="<img src='images/closebutton.jpg', title='Order Status' border='0' height='24' width='24'></img>";
if ($rest == "Close")
$status_change ="<a id='$id', href='#' class = 'status_button' title='Open'>";
else
$status_change= "<a id='$id', href='#' class = 'status_button' title='Close'>";
echo "$image;$status_change";
?>
$('.status_button').click(function(){
should be:
$(document).on('click', '.status_button', function(){
http://api.jquery.com/on/
And...
echo "$image;$status_change";
go to:
echo $image.";".$status_change.";";
make openbutton & closebutton changes in the first page
like this
<div id='message'><img src='images/closebutton.jpg' id='message' title='Order Status' border='0' height='24' width='24'></img></div>
<script>
$('img#message').click(function(){
var messageimage;
messageimage = $('img#message').attr();
if(messageimage == 'images/closebutton.jpg'){
$('img#message').attr('src','images/openbutton.jpg');
}else{
$('img#message').attr('src','images/closebutton.jpg');
}
});
</script>