Get response from PHP code by Ajax - javascript

I try to send the data from the HTML form to php code by Ajax and it does not get the response
the html form get user_id from the user entry then send it by java script function that handle ajax code and send the user_id to php code to get user_id by $user_id = $_GET['user_id']; and search by the user_id then show what ever in php code in the other html code to show div content showdocument.getElementById("content").innerHTML=xmlhttp.responseText; response from php
function showUser(str) {
if (str == "") {
document.getElementById("content").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "http://localhost/gpms/admin_modify_user.php?user_id=" + str, true);
xmlhttp.send();
}
<head>
<script src="http://localhost/gpms/admin_user.js"></script>
</head>
<body>
<form method=post>
<label> Enter User ID: </label>
<input id="user_id" type=text name=user_id>
<br><br>
<input id="modify" type=submit value=Modify onclick="<script>showUser(user_id);</script>">
</form>
</body>
<?php
$user_id = $_GET['user_id'];
//create connection
$conn = mysqli_connect("localhost","root","","gpms");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM user WHERE user_id = '$user_id' ";
$result = mysqli_query($conn, $sql);
if (mysqli_query($conn, $sql)) {
$row = mysqli_fetch_assoc($result);
if ($row == 0) {
echo "No Results";
}
else {
$id = $row['user_id'];
$name = $row['user_name'];
$password = $row['user_password'];
$email = $row['user_email'];
$department = $row['user_department'];
echo "<div id = demo>";
echo "<table>";
echo "<tr>";
echo "<td> ID </td><td> Name </td><td> Password </td><td> E-mail </td><td> Department </td>";
echo "</tr>";
echo "<tr>";
echo '<td> '. $id .' </td><td> '. $name .' </td><td> '. $password .' </td><td> '. $email .' </td><td> '. $department .' </td>';
echo "</tr>";
echo "</table>";
echo "<button onclick = 'editUser(\"$id\",\"$name\",\"$password\",\"$email\",\"$department\")' > Edit </button>";
echo "<button onclick = 'deleteUser(".$id.")' > Delete </button>";
echo "</div>";
}
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
$conn->close();
?>

Your onclick attribute is wrong. It should just be the Javascript code, it shouldn't have <script>...</script> around it.
<input id="modify" type=submit value=Modify onclick="showUser(user_id);">
If you had looked in your Javascript console you would have seen it complain of a syntax error when you clicked.
And in the PHP, this line:
if (mysqli_query($conn, $sql)) {
should be:
if ($result) {
Otherwise you do the same query twice, which is unnecessary.

Related

Store name and value of a Button in a mysql table row

I've been hanging on this problem for 3 days and just can't solve it. It seems relatively simple, but unfortunately, I can't do it, because I'm a noob.
I would like to use the button's onclick function to get its 2 pieces of information
```html
<input id="'.$row['id'].'" type="button" value="Pause" name="'.$row['name'].'" onclick="pushDataToDB()">```
name = "'. $ row [' name '].'" [the name reference from a database
table]
and value="Pause"
this two informations i would like to store in some other database table.
I have tried to solve this problem in different ways.
I have tried to store in different ways the event.target.name & event.target.event javascript output in PHP Variables and then use it in the mysql insert line but i failed.
I have tried to post the value to the ajax.php then store the value in a PHP variable and use this as Value to push it to the database, but this also doesn't work
index.php
<div class="button2">
<form action="ajax.php" method="POST">
<input id="'.$row['id'].'" type="button" value="Pause" name="'.$row['name'].'" onclick="pushDataToDB()">
</Form>
</div>'
script.js:
function pushDataToDB() {
$.get("ajax.php");
return false;
}
ajax.php
<?php
include_once ('dbh.php');
if(isset($_POST['name'])){
$sqlAufPause = "INSERT INTO aktuellaufpause (name, pausenart) VALUES ('$name', 'BP')";
}
if ($conn->query($sqlAufPause) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
I would say this is the reason, why the name Value is empty,
but i don't know how to fix ist..
emptyNameValue
You can use JQuery + AJAX to perform asynchronous POST
<?php
$con = mysqli_connect("localhost", "root", "", "testdb");
$query = mysqli_query($con, "SELECT * FROM mytable WHERE id = 1");
$row = mysqli_fetch_assoc($query);
print_r($row);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="button2">
<form id="frm">
<input id="<?php echo $row['id'] ?>" type="button" value="Pause" name="<?php echo $row['name'] ?>" onclick="pushDataToDB()">
</Form>
</div>
</body>
<script type="text/javascript">
function pushDataToDB() {
var name = "<?php echo $row['name'] ?>";
var value = "Pause";
$.ajax({
url: "ajax.php",
type: "POST",
data: {
"name": name,
"value": value
},
success: function(e) {
if (e == "1") {
alert("Success!");
} else {
alert("error!");
}
}
});
}
</script>
</html>
ajax.php
<?php
$con = mysqli_connect("localhost", "root", "", "testdb");
$name = $_POST['name'];
$value = $_POST['value'];
$query = "INSERT INTO mytable(name, value) values('$name','$value')";
$result = mysqli_query($con, $query);
if ($result) {
echo "1";
} else {
echo "Error!";
}
EDITTTT****
I changed
var name = "<?php echo $row['id'] ?>";
to
var name = "<?php echo $row['name'] ?>";
since it is the "name" you want stored in the database
I solved the problem this way.
Thank you so much!!!
index.php
<?php
$sql = "SELECT * FROM `DB-TABLENAME` ORDER BY `VALUE1`, `VALUE2`";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td>";
echo '<input style="margin: 0 auto 6px 17px;" type="checkbox" id="scales" name="scales">';
echo "</td>";
echo "<td>";
echo $row['VALUE1'];
echo "</td>";
echo "<td>";
echo $row['VALUE2'];
echo "</td>";
echo "<td>";
echo '<div class="button1">
<input id="'.$row['id'].'" type="button" value="BP" name="'.$row['VALUE2'].'" onclick="pushDataToDB()">
</div>';
echo "</td>";
echo "<td>";
echo '<div class="button2">
<form id="frm">
<input id="'.$row['id'].'" type="button" value="Mittagspause" name="'.$row['name'].'" onclick="pushDataToDB()">
</form>
</div>';
echo "</td>";
echo "</tr>";
}
} else {
echo "there are no comments";
}?>
<script type="text/javascript">
function pushDataToDB() {
var name = event.target.name;
var value = event.target.value;
$.ajax({
url: "ajax.php",
type: "POST",
data: {
"name": name,
"value": value
},
success: function(e) {
if (e == "1") {
alert("Success!");
} else {
alert("error!");
}
}
});
}
</script>
ajax.php
<?php
include_once('dbconnectioncredentials.php');
$con = mysqli_connect($servername, $username, $password, $dbname);
$name = $_POST['VALUE1'];
$value = $_POST['VALUE2'];
$query = "INSERT INTO aktuellaufpause (VALUE1, VALUE2) VALUES ('$name','$value')";
$result = mysqli_query($con, $query);
if ($result) {
echo "1";
} else {
echo "Error!";
}
?>

How do I run a click event for a php created html table

I have php creating a table based on the results of a search and this table overwrites a previous table. When clicking a row of this table I want the details of the row to be displayed. However while clicking on the previous table works when clicking on the results table the click event is not triggered.
The initial table code and containing div:
<div id="fixInfo" style="overflow-y: auto; overflow-x:hidden;max-height:350px; width: 1000px;">
<table class="standard" id= "list">
<?php
include 'DATA.php';
$sql = "SELECT * FROM FIX";
$result = mysqli_query($conn, $sql);
if ($result = mysqli_query($conn, $sql)){
while ($row = mysqli_fetch_assoc($result)){
echo '<tr>';
echo '<td style="width:150px;">'.$row["FIX_ID"].'</td>';
echo '<td style="width:150px;">'.$row["TIME"].'</td>';
echo '<td style="width:150px;">'.$row["DATE"].'</td>';
echo '<td style="width:150px;">'.$row["PROVIDER_ID"].'</td>';
echo '</tr>';
}
}
mysqli_close($conn);
?>
</table>
</div>
The jquery click event code:
<script>
$("#list tr").on("click",function(){
var ID = $(this).find("td:first").text();
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
document.getElementById("fixstuff").innerHTML = this.responseText;
}
};
var params= "ID="+ID;
xmlhttp.open("POST","fixdetails.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
});
</script>
The result table creation code(searchFix.php):
<?php
$sort = $_POST['sort'];
$search= $_POST['search'];
include 'DATA.php';
if($search==""){
$sql = "SELECT * FROM FIX";
}
else{
$sql= "SELECT * FROM FIX WHERE ".$sort." =". $search;
}
$result = mysqli_query($conn, $sql);
if ($result = mysqli_query($conn, $sql)){
while ($row = mysqli_fetch_assoc($result)){
echo '<tr>';
echo '<td style="width:150px;">'.$row["FIX_ID"].'</td>';
echo '<td style="width:150px;">'.$row["TIME"].'</td>';
echo '<td style="width:150px;">'.$row["DATE"].'</td>';
echo '<td style="width:150px;">'.$row["PROVIDER_ID"].'</td>';
echo '</tr>';
}
}
mysqli_close($conn);
?>
As you are altering the dom you will need to do a rebind.
$.on does not work the same as the deprecated $.live
try changing initial line to
$(document).on('click','#list tr', {} ,function(e){

How to search keywords in PHP?

I have a script. It work fine with against & exact match, but when I search with multiple keywords, it returns null and black page against my query.
Here is my code:
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
</head>
<body>
<?Php
ini_set('display_errors', true);//Set this display to display all erros while testing and developing the script
error_reporting(0);// With this no error reporting will be there
include "include/z_db.php";
$todo=$_POST['todo'];
$search_text=$_POST['search_text'];
if(strlen($serch_text) > 0){
if(!ctype_alnum($search_text)){
echo "Data Error";
exit;
}
}
////////// Displaying the search box /////
echo "<table>
<tr><td colspan=2 align='center'>";
echo "<form method=post action=''><input type=hidden name=todo value=search>
<input type=text name=search_text value='$search_text'><input type=submit value=Search><br>
<input type=radio name=type value=any checked>Match any where
<input type=radio name=type value=exact>Exact Match
</form>
";
echo "</td></tr>";
/////////// if form is submitted the data processing is done here///////////////
echo "<tr><td width='600' valign=top>";
if(isset($todo) and $todo=="search"){
$type=$_POST['type'];
$search_text=ltrim($search_text);
$search_text=rtrim($search_text);
if($type<>"any"){
$query="select * from student where name='$search_text'";
}else{
$kt=split(" ",$search_text);//Breaking the string to array of words
// Now let us generate the sql
while(list($key,$val)=each($kt)){
if($val<>" " and strlen($val) > 0){$q .= " name like '%$val%' or ";}
}// end of while
$q=substr($q,0,(strLen($q)-3));
// this will remove the last or from the string.
$query="select * from student where $q ";
} // end of if else based on type value
echo "<span style='background-color= #FFFF00'>$query</span><br>";
$count=$dbo->prepare($query);
$count->execute();
$no=$count->rowCount();
if($no > 0 ){echo " No of records = ".$no."<br><br>";
echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>";
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td>
<td>$row[mark]</td><td>$row[sex]</td></tr>";
}
echo "</table>";
}else {
echo " No records found ";
}
}// End if form submitted
echo "</td><td width='400' valign=top>";
echo " Full records here ";
$query="select * from student";
echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>";
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td>
<td>$row[mark]</td><td>$row[sex]</td></tr>";
}
echo "</table>";
echo "</td></tr></table>";
?>
</body>
</html>
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>Demo of Search Keyword using PHP and MySQL</title>
</head>
<body>
<?Php
ini_set('display_errors', true);//Set this display to display all erros while testing and developing the script
error_reporting(0);// With this no error reporting will be there
include "include/z_db.php";
$todo=$_POST['todo'];
$search_text=$_POST['search_text'];
if(strlen($serch_text) > 0){
if(!ctype_alnum($search_text)){
echo "Data Error";
exit;
}
}
////////// Displaying the search box /////
echo "<table>
<tr><td colspan=2 align='center'>";
echo "<form method=post action=''><input type=hidden name=todo value=search>
<input type=text name=search_text value='$search_text'><input type=submit value=Search><br>
<input type=radio name=type value=any checked>Match any where
<input type=radio name=type value=exact>Exact Match
</form>
";
echo "</td></tr>";
/////////// if form is submitted the data processing is done here///////////////
echo "<tr><td width='600' valign=top>";
if(isset($todo) and $todo=="search"){
$type=$_POST['type'];
$search_text=ltrim($search_text);
$search_text=rtrim($search_text);
if($type<>"any"){
$query="select * from student where name='$search_text'";
}else{
$kt=split(" ",$search_text);//Breaking the string to array of words
// Now let us generate the sql
while(list($key,$val)=each($kt)){
if($val<>" " and strlen($val) > 0){$q .= " name like '%$val%' or ";}
}// end of while
$q=substr($q,0,(strLen($q)-3));
// this will remove the last or from the string.
$query="select * from student where $q ";
} // end of if else based on type value
echo "<span style='background-color= #FFFF00'>$query</span><br>";
$count=$dbo->prepare($query);
$count->execute();
$no=$count->rowCount();
if($no > 0 ){echo " No of records = ".$no."<br><br>";
echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>";
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td>
<td>$row[mark]</td><td>$row[sex]</td></tr>";
}
echo "</table>";
}else {
echo " No records found ";
}
}// End if form submitted
echo "</td><td width='400' valign=top>";
echo " Full records here ";
$query="select * from student";
echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>";
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td>
<td>$row[mark]</td><td>$row[sex]</td></tr>";
}
echo "</table>";
echo "</td></tr></table>";
?>
</body>
</html>
MySQL Connection:
<?php
global $dbo;
$info['dbhost_name'] = "localhost";
$info['database'] = "search"; // database name
$info['username'] = "root"; // userid
$info['password'] = ""; // password
$dbConnString = "mysql:host=" . $info['dbhost_name'] . "; dbname=" . $info['database'];
$dbo = new PDO($dbConnString, $info['username'], $info['password']);
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
//$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$error = $dbo->errorInfo();
if($error[0] != "") {
echo "string";
}
?>
Result after query submitted:
$q = array(); // create an array
$sq = ""; // this variable will be used in the query
if(isset($_POST['txt_projectname']) && !empty($_POST['txt_projectname'])){
$projectname = mysqli_real_escape_string($conn,$_POST['txt_projectname']);
$q[] = "db_projectname='".$projectname."' ";
} // take the variable from input after submit and put it in the array
if(isset($_POST['txt_location']) && !empty($_POST['txt_location'])){
$location = mysqli_real_escape_string($conn,$_POST['txt_location']);
$q[] = "db_location='".$location."' ";
}
$first = true;
foreach($q as $qu){
if($first){
$sq .= " where ".$qu;
$first = false;
}else{
$sq .= " and ".$qu;
} // for loop to use where and and in the query
}
$sql=mysqli_query($conn,"select * from table {$sq} ")or die(mysqli_error($conn));
You can do something like this

Send multiple variable with PHP AJAX GET onclick of a button

I have two dynamically loaded dropdowns: one containing golf course holes information and another holding users- together the information will be used to generate a scorecard.
When the course is selected and a user is selected I want to click a button and then this will generate the scorecard.
Below is the code for the 'course' dropdown
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT courseID, name FROM courses";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result))
{
$courses[] = '<option value="'.$row['courseID'].'">'.$row['name'].'</option>';
}
?>
Below is the code for the 'user' dropdown
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT userID, forename, surname FROM user";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result))
{
$users[] = '<option value="'.$row['userID'].'">'.$row['forename'].' '.$row['surname'].'</option>';
}
?>
Below is the HTML code for the dropdowns
<form>
<select id="selectCourse" onchange="showCourse(this.value)">
<option value = "">Select Course</option>
<?php foreach($courses as $c){
echo $c;
}?>
</select>
<select id="selectUser" >
<option value = "">Select User</option>
<?php foreach($users as $u){
echo $u;
} ?>
</select>
<button type="button" >Click me</button>
</form>
At the moment I have code that uses the 'onchange' to load the first part of the scorecard which contains the hole information about that course. I am having problems changing this to the click of the button and also consider another variable from the user dropdown.
The below code is taken from W3Schools which loaded the hole information correctly based on 'onchange'.
<script>
function showCourse(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","generateSC.php?cValue="+str,true);
xmlhttp.send();
}
}
</script>
The below code shows the first half of the scorecard being generated from the selection of the first dropdown.
<?php
$cValue = mysql_real_escape_string($_GET['cValue']);
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT DISTINCT holeNumber, strokeIndex, par FROM holes WHERE courseID= '".$cValue."'";
$result = mysqli_query($con,$sql) or die("Error: ".mysqli_error($con));
echo '<div class="scorecardTable">
<table>
<tr>
<th>HoleNumber</th>
<th>Par</th>
<th>Stroke Index</th>
<th>Score</th>
<th>Points</th>
</tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['holeNumber'] . "</td>";
echo "<td>" . $row['par'] . "</td>";
echo "<td>" . $row['strokeIndex'] . "</td>";
echo "<td> <input required type=text /></td>";
echo "<td> </td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
What I am looking to know is can I pass two variables through at this point below:
xmlhttp.open("GET","generateSC.php?cValue="+str,true);
and if so how would I get the second variable.
EDIT
<script>
function showCourse(course, user) {
var user = document.getElementById('selectUser').value;
var course = document.getElementById('selectCourse').value;
if (user || course == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","generateSC.php?course="+course+"&user="+user,true);
xmlhttp.send();
}
}
</script>
I've updated what I have above... the problem now is how do i get the button to work with the two variables?
<form>
<select id="selectCourse">
<option value = "">Select Course</option>
<?php foreach($courses as $c){
echo $c;
}?>
</select>
<select id="selectUser" >
<option value = "">Select User</option>
<?php foreach($users as $u){
echo $u;
} ?>
</select>
<button type="button" >Click me</button>
</form>
Just fetch the values from both dropdowns and concatinate the URL:
var user = document.getElementById('selectUser').value;
var course = document.getElementById('selectCourse').value;
xmlhttp.open("GET","generateSC.php?cValue="+course+"&user="+user,true);
Then your generateSC php script will of course have to fetch the value from the user parameter and work with that as well.
$_GET['user'] will fetch the value from the user parameter.

Validate PHP variable via Javascript

Im looking to pass one variable from my PHP code to my Javascript code to validate a figure. I'm creating a shopping cart scenario whereby i have a variable 'in_stock' which specifies the amount of stock available for a product. If I enter an amount that is greater than the 'in_stock' available i need an error to be thrown. This is currently what I have:
Java Script
<script language="javascript">
function numCheck()
{
var enteredChar = document.getElementById('add_value').value;
var stockavailable ="<?php echo $stock?>";
//To check if a non-numerical value is entered
if (isNaN(enteredChar))
{
alert("Not a Number!");
return false;
}
//To check if the input is empty
if (enteredChar=="")
{
alert("Empty!");
return false;
}
//To check if the amount entered is not greater than the amount in stock
if (enteredChar > stockavailable)
{
alert("Not enough in stock");
return false;
}
}
</script>
This is all occurring whilst my PHP has called the database and returned the value on the screen. As follows:
PHP
$product_id =(int)$_GET['product_id'];
$username = "potiro";
$password = "pcXZb(kL";
$hostname = "rerun";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("poti",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM products where product_id=$product_id");
echo '<form name="form1">';
echo '<table class="Grocery-table">';
while($row = mysql_fetch_array($result))
{
$stock =$row['in_stock'];
$product_id = $row['product_id'];
echo "<tr><td><b>Product ID</b></td>";
echo "<td>";
echo $product_id;
echo "</td></tr>";
echo "<tr><td><b>Product Name</b></td>";
echo "<td>";
echo $row['product_name'];
echo "</td></tr>";
echo "<tr><td><b>Unit Price</b></td>";
echo "<td>";
echo $stock;
echo "</td></tr>";
echo "<tr><td><b>Unit Quantity</b></td>";
echo "<td>";
echo $row['unit_quantity'];
echo "</td></tr>";
echo "<tr><td><b>In Stock</b></td>";
echo "<td>";
echo $row['in_stock'];
echo "</td></tr>";
echo '<tr><td><b>Add</b></td><td><Input type="text" id="add_value" name="cart"></input></td></tr>';
echo '<tr><td></td><td><input type="submit" value="Submit" onclick="return numCheck()"></td></tr>';
}
echo "</table>";
echo "</form>";
mysql_close($dbhandle);
?>
add your stock value to a hidden input value stock_value
echo '<tr><td><b>Add</b></td><td><Input type="text" id="add_value" name="cart" ></input><Input type="hidden" id="stock_value" name="stock_value" value="'.trim($stock).'"></input></td></tr>';
echo '<tr><td></td><td><input type="submit" value="Submit" onclick="return numCheck()"></td></tr>';
in javascript
<script language="javascript">
function numCheck()
{
var enteredChar = document.getElementById('add_value').value;
var stockavailable =document.getElementById('stock_value').value;

Categories