enter image description here
The above image due value 19948 and the input value are not greater than the due value 19948. How to validate this in javascript or jquery or php?
<?php
$i = 0;
$sql = "select * from invoice where `cid`='5'";
$res = mysql_query($sql);
$numrows = mysql_num_rows($res);
while ($row = mysql_fetch_array($res)) {
$i = $i + 1;
echo "<tr>";
echo "<td>" . $row['customername'] . "</td>";
echo "<td>" . $row['totalamount'] . "</td>";
echo "<td>" . $row['paidamount'] . "</td>";
echo "<td>" . $row['dueamount'] . "</td>";
?>
<?php
echo "<td><input type='text' name='ichange$i' value='0' onkeyup='ivalue()' />
<input type='hidden' name='idue$i' value='$due' /></td>";
echo "</td>";
echo "</tr>";
}
echo "<input type='hidden' name='nrows' value='$numrows' />";
?>
<script>
function ivalue()
{
nrows=document.getElementsByName("nrows").item(0).value;
for(i=1;i<=nrows;i++)
{
ichange="ichange" + i;
idue="idue" + i;
if(document.getElementsByName(ichange).item(0).value>document.getElementsByName(idue).item(0).value)
{
alert("Value not greater than due value")
}
}
}
</script>
I suppose you want to alert the user if he enters a greater value than the due in the same row.
I would use jQuery here since you tagged it :
$('input[type="text"]').on('keyup',function(){
if($(this).val() > $(this).next().val()){
alert("Value not greater than due value")
}
})
You could add some classes to your html for an easier and more precise select.
Related
I have a php website that makes a table using data fetched from a database. In the table I have a input so that the user can select how many of each item they want to buy. I have successfully made the ids of each input different by concatenating the ids.
Here is the php that makes the table:
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['Article'] . "</td>";
echo "<td>" . $row['Prix'] . "</td>";
echo "<td>" . $row['PrixRetour'] . "</td>";
echo "<td>" . $row['QuantiteeMaximale'] . "</td>";
echo "<td>" . $row['Projet'] . "</td>";
echo "<td id=\"quantity" . $row['id'] . "\"><input type=\"number\" name=\"quantity\" id=\"quantity\"></td>";
echo "</tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I need to write the total amount at the end of my table, but i don't know how to make a for loop in javascript so that the number in the input field is multiplied by the price. Is there an easy part of code that i could use to calculate the grand total price?
You don't need to do this in Javascript. You could just do it in your PHP code:
<?php
if ($result->num_rows > 0) {
$grandTotal = 0;
// output data of each row
while($row = $result->fetch_assoc()) {
$grandTotal += $row['Prix'] * $row['QuantiteeMaximale'];
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['Article'] . "</td>";
echo "<td>" . $row['Prix'] . "</td>";
echo "<td>" . $row['PrixRetour'] . "</td>";
echo "<td>" . $row['QuantiteeMaximale'] . "</td>";
echo "<td>" . $row['Projet'] . "</td>";
echo "<td id=\"quantity" . $row['id'] . "\"><input type=\"number\" name=\"quantity\" id=\"quantity\"></td>";
echo "</tr>";
}
echo "Grand Total: {$grandTotal}"; // you might want to end your table before this. I'll leave formatting up to you.
} else {
echo "0 results";
}
$conn->close();
?>
Also, here's a cleaner way to output your HTML:
<?php
if ($result->num_rows > 0) {
$grandTotal = 0;
// output data of each row
while($row = $result->fetch_assoc()) {
$grandTotal += $row['Prix'] * $row['QuantiteeMaximale'];
?>
<tr>
<td><?= htmlentities($row['id']); ?></td>
<td><?= htmlentities($row['Article']); ?></td>
<td><?= htmlentities($row['Prix']); ?></td>
<td><?= htmlentities($row['PrixRetour']); ?></td>
<td><?= htmlentities($row['QuantiteeMaximale']); ?></td>
<td><?= htmlentities($row['Projet']); ?></td>";
<td id="quantity<?= $row['id']; ?>"><input type="number" name="quantity"></td>
</tr>
<?php
}
echo "Grand Total: {$grandTotal}"; // you might want to end your table before this. I'll leave formatting up to you.
} else {
echo "0 results";
}
$conn->close();
?>
If you want to use the quantity field in the table itself, you could do something like this. It's a pretty quick solution. You'd probably want to refine it. But it's at least something to work with.
<?php
if ($result->num_rows > 0) {
echo "<table id='items'>";
// output data of each row
while($row = $result->fetch_assoc()) {
$grandTotal += $row['Prix'] * $row['QuantiteeMaximale'];
?>
<tr>
<td><?= htmlentities($row['id']); ?></td>
<td><?= htmlentities($row['Article']); ?></td>
<td><?= htmlentities($row['Prix']); ?></td>
<td><?= htmlentities($row['PrixRetour']); ?></td>
<td><?= htmlentities($row['QuantiteeMaximale']); ?></td>
<td><?= htmlentities($row['Projet']); ?></td>";
<td><input data-price='<?= floatval($row['Prix']); ?>' data-max-quantity='<?= intval($row['QuantiteeMaximale']); ?>' type="number" name="quantity"></td>
</tr>
<?php
}
?>
</table>
<p>Grand Total: $<span id='grandTotal'></span></p>
<script>
(() => {
const updateGrandTotal = (grandTotalEl, inputEls) => {
grandTotalEl.innerText = inputEls.reduce((total, inputEl) => {
const maxQuantity = parseInt(inputEl.dataset.maxQuantity)
if(parseInt(inputEl.value) > maxQuantity) inputEl.value = maxQuantity
if(parseInt(inputEl.value) < 0) inputEl.value = 0
const price = parseFloat(inputEl.dataset.price)
const quantity = parseInt(inputEl.value)
if(isNaN(quantity)) return total
return total + (price * quantity)
}, 0)
}
const tableEl = document.getElementById('items')
const grandTotalEl = document.getElementById('grandTotal')
const quantityInputEls = tableEl.querySelectorAll('input[name=quantity]')
quantityInputEls.forEach(el => el.addEventListener('keyup', () => updateGrandTotal(grandTotalEl, inputEls)))
})()
</script>
<?php
} else {
echo "0 results";
}
$conn->close();
?>
I have a table that is populated by data from a mysql database and i need to be able to click on certain columns of the table to sort them ascending and descending, im not sure how to go about this if i can use php html or javascript , i will attach an image to show what i already have to give a better idea of what im talking about
https://imgur.com/a/ypnNxB0
<?php
$connection = mysqli_connect('localhost', 'root', '','nba201819'); //The Blank string is the password
$result = mysqli_query($connection,"SELECT * FROM `teamstats` ORDER BY `teamstats`.`WIN%` DESC");
?>
<table id="teamstats" border ='2'>
<tr>
<th></th>
<th>Code</th>
<th>Team</th>
<th>GP</th>
<th>W</th>
<th>L</th>
<th><a href='?sortBy=WIN%'>WIN%</th>
<th>MIN</th>
<th><a href='?sortBy=PTS'>PTS</th>
<th><a href='?sortBy=FGM'>FGM</th>
<th>FGA</th>
<th>FG%</th>
<th><a href='?sortBy=3PM'>3PM</th>
<th>3P%</th>
<th><a href='?sortBy=FTM'>FTM</th>
<th>FTA</th>
<th>FT%</th>
<th>OREB</th>
<th>DREB</th>
<th><a href='?sortBy=REB'>REB</th>
<th>AST</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td><img src='logos/".$row['TEAMCODE']."_logo.svg' width =20 height=20></td>" ;
echo "<td>" . $row['TEAMCODE'] . "</td>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['GP'] . "</td>";
echo "<td>" . $row['W'] . "</td>";
echo "<td>" . $row['L'] . "</td>";
echo "<td>" . $row['WIN%'] . "</td>";
echo "<td>" . $row['MIN'] . "</td>";
echo "<td>" . $row['PTS'] . "</td>";
echo "<td>" . $row['FGM'] . "</td>";
echo "<td>" . $row['FGA'] . "</td>";
echo "<td>" . $row['FG%'] . "</td>";
echo "<td>" . $row['3PM'] . "</td>";
echo "<td>" . $row['3P%'] . "</td>";
echo "<td>" . $row['FTM'] . "</td>";
echo "<td>" . $row['FTA'] . "</td>";
echo "<td>" . $row['FT%'] . "</td>";
echo "<td>" . $row['OREB'] . "</td>";
echo "<td>" . $row['DREB'] . "</td>";
echo "<td>" . $row['REB'] . "</td>";
echo "<td>" . $row['AST'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
There are various js plugins to help achieve data table sorting such as easyui, datatables etc.
If you only want to achieve it with simple code like you provided, you have to retrieve the sortBy variable and put it in your SQL query:
$connection = mysqli_connect('localhost', 'root', '','nba201819'); //The Blank string is the password
if (isset($_GET['sortBy'])) {
if ($_GET['sortBy'] !== '') {
$sortBy = str_replace( "`", "``", $_GET['sortBy']);
} else {
$sortBy = 'WIN%';
}
} else {
$sortBy = 'WIN%';
}
$result = mysqli_query($connection,"SELECT * FROM `teamstats` ORDER BY `teamstats`.`$sortBy` DESC");
I have a program that displays authors book code and book title using php and
AJAX technology, but for some reason the data is not appearing in the table. I know my SQL code is correct as our instructor gave us the code for that, but something is preventing the data from appearing in the table. Any tips or suggestions would be appreciated!
<body>
<?php
$authorid = 0;
$authorid = (int) $_GET['authorid'];
if ($authorid > 0) {
require_once('dbtest.php');
$query = "SELECT * FROM author";
$r = mysqli_query($dbc, $query);
if (mysqli_num_rows($r) > 0) {
$row = mysqli_fetch_array($r);
} else {
echo "Title Not Returned<br>";
}
echo "<table border='1'><caption>Titles for </caption>";
echo "<tr>";
echo "<th>Book Code</th>";
echo "<th>Book Title</th>";
echo "</tr>";
$q2 ="SELECT wrote.author_number As ANo, wrote.book_code As BookCd, book.book_title As Title ";
$q2 .= " FROM wrote, book ";
$q2 .= " WHERE wrote.book_code=book.book_code ";
$q2 .= " AND wrote.author_number = ' ' ";
$q2 .= " ORDER BY book.book_title";
$r2 = mysqli_query($dbc, $q2);
$row = mysqli_fetch_array($r2);
while ($row) {
echo "<tr>";
echo "<td>" .$row['BookCd']. "</td>";
echo "<td>" .$row['Title']. "</td>";
echo "</tr>";
$row = mysqli_fetch_array($r2);
}
echo "</table>";
} else {
echo "<p>No Author ID from prior page</p>";
}
?>
</form>
</body>
The suspicious line is: AND wrote.author_number = ' '
Why is it empty?
Put a check after the second query:
$r2 = mysqli_query($dbc, $q2);
if (mysqli_num_rows($r2) > 0) {
echo "rows are Returned<br>";
} else {
echo "rows are Not Returned<br>";
}
$row = mysqli_fetch_array($r2);
<?php
include_once("db.php");
$result=mysql_query("SELECT * FROM stu WHERE receiver='DM4'");
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['ptype'] . "</td>";
echo "<td>" . $row['source'] . "</td>";
echo "<td>" . $row['letterno'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['descrip'] . "</td>";
echo "<td>" . $row['receiver'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td><a href='vex.php?uid={$row['letterno']}' id='id' onClick='addfavourite()'>.{$row['title']}.</a></td>";
//echo "<td><a href='update.php?id={$row['id']}'>Update</a></td>";
echo"<td><img style='width:100px;higth:150px;' src='upload/{$row[image]}'></td>";
addfavourite();
echo addfavourite();
function addfavourite() {
$ide=$_GET['uid'];
//echo $ide;
$sql = "SELECT * FROM stu WHERE letterno = '$ide'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if($row){
$newfav = "UPDATE stu SET open = 1 WHERE letterno = '$ide'";
$createfav = mysql_query($newfav);}
else{
$newfav = "UPDATE stu SET open = 0 WHERE letterno = '$ide'";
$createfav = mysql_query($newfav);}
}
}
echo $ide;
?>
This is my error code.In this code,there is a fault with mysql query statement.it is not supported with the databse. but onclick() function is working.
You cannot directly execute a PHP function from a JavaScript event. Simply, cannot mix server side and client side logic but you can make two of them interact with each other.
In this case, you can create a JavaScript function which sends an AJAX request to a PHP page on your server containing the code of addfavourite().
A Demo
I haven't tested the code below but assuming that your code logic and rest stuff is correct, this might just work
demo.php
<script>
function addfavourite(uid){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
var url = "addfavourite.php"; // URL of your PHP file
var vars = "uid="+uid;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
<?php
include_once("db.php");
$result=mysql_query("SELECT * FROM stu WHERE receiver='DM4'");
echo "<table>";
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['ptype'] . "</td>";
echo "<td>" . $row['source'] . "</td>";
echo "<td>" . $row['letterno'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['descrip'] . "</td>";
echo "<td>" . $row['receiver'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td><a href='#' id='id' onClick='addfavourite({$row['letterno']})'>.{$row['title']}.</a></td>";
echo"<td><img style='width:100px;higth:150px;' src='upload/{$row[image]}'></td>";
}
echo "</table>";
?>
<div id='status'></div>
addfavourite.php
<?php
if(!isset($_POST['uid'])) {
$ide = $_POST['uid'];
$sql = "SELECT * FROM stu WHERE letterno = '$ide'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row) {
$newfav = "UPDATE stu SET open = 1 WHERE letterno = '$ide'";
$createfav = mysql_query($newfav);
} else {
$newfav = "UPDATE stu SET open = 0 WHERE letterno = '$ide'";
$createfav = mysql_query($newfav);
}
if ($createfav) {
echo "<script>alert('Added to favourite successfully...')";
} else {
echo "<script>alert('Something went wrong...')";
}
}else{
echo "POST variable not set!";
}
?>
Some notes
You should use mysqli insted of mysql functions as it is deprecated and no longer supported
This here is a good video tutorial on AJAX https://www.developphp.com/video/JavaScript/Ajax-Post-to-PHP-File-XMLHttpRequest-Object-Return-Data-Tutorial
i have a ajax function that is returning a set of values from php page.
i need to get the values to that is only required. how can i do this
ajax.js
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
ajax.php
<?php
require_once('config.php');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM thr';
mysql_select_db($dbname);
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo "<table border='1'>";
while($row = mysql_fetch_assoc($retval))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['ther_name'] . "</td>";
echo "<td>" . $row['region'] . "</td>";
echo "<td>" . $row['phone_no'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td id='lat'>" . $row['corrd_lattitude'] . "</td>";
echo "<td id='lon'>" . $row['corrd_longitude'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($conn);
?>
i need only values of
$row['corrd_lattitude']
$row['corrd_longitude']
how to get the values of this
first you can fetch only required values from table..if i understood correctly you can use following query.
$sql = 'SELECT corrd_lattitude,corrd_longitude FROM thr';
it will return only tw0 column value from table.
$json = json_encode(array($row['corrd_lattitude'], $row['corrd_longitude']));
echo $json;
You could specify parameters with your request.
In GET method:
ajax.php?corrd_lattitude=true&corrd_longitude=true
and in php file you can check this in $_GET array ie:
<?php
[...]
echo "<table border='1'>";
while($row = mysql_fetch_assoc($retval))
{
echo "<tr>";
if ($_GET['id'] == true) {
echo "<td>" . $row['id'] . "</td>";
}
if ($_GET['ther_name'] == true) {
echo "<td>" . $row['ther_name'] . "</td>";
}
if ($_GET['region'] == true) {
echo "<td>" . $row['region'] . "</td>";
}
if ($_GET['phone_no'] == true) {
echo "<td>" . $row['phone_no'] . "</td>";
}
if ($_GET['address'] == true) {
echo "<td>" . $row['address'] . "</td>";
}
if ($_GET['corrd_lattitude'] == true) {
echo "<td id='lat'>" . $row['corrd_lattitude'] . "</td>";
}
if ($_GET['corrd_longitude'] == true) {
echo "<td id='lon'>" . $row['corrd_longitude'] . "</td>";
}
echo "</tr>";
}
echo "</table>";
mysql_close($conn);
?>
Better is use json (or plain values) instead of html - your js should pack values into html. It's better for server, client side should build html. Sry for my english.
use json:-----------
=========================================
$sql = "SELECT * FROM thr";
$rs = mysql_query($sql);
$res = mysql_fetch_assoc($rs);
if(mysql_num_rows($rs)>0){
echo json_encode(array('lats'=>$res['corrd_lattitude'],'lngs'=>$res['corrd_longitude']));
}else{
echo json_encode(array('lats'=>'','lngs'=''));
}
here lats and lngs are simply varaiable name to store values inside them and get the value on other page from lats and lngs varaibale.