Check the input quantity is greater than the available quantity in database - javascript

What I want to do is checking whether the text box input quantity is greater than the available quantity in database. Alert should be displayed onclick() of the ADD button.
ADD button
<button type="button" name="btnSave" id="btnSave" onclick="submitdata(); resetform(); checkQty();">ADD</button>
checkQty() function
function checkQty() {
//Grab current forms input field values.
var txtQuantity = document.getElementById("txtQuantity").value;
var listItemName = document.getElementById("listItemName").value;
//Connect to database and verify Quantity Ordered isnt greater than Quantity In Stock.
$.ajax({
type: "POST",
url: "/pms/includes/functions/qty_check.php",
data: 'listItemName=' + listItemName + '&txtQuantity=' + txtQuantity,
}).responseText;
}
qty_check.php
<?php
error_reporting(E_ALL );
ini_set('display_errors', 1);
//Start the Session
if(!isset($_SESSION))
{
session_start();
}
include_once("../../config.php");
require __DIR__."../../dbutil.php";
if(!empty($_POST['txtQuantity'])){$qty = $_POST['txtQuantity'];}
if(!empty($_POST['listItemName'])){$item = $_POST['listItemName'];}
$results = mysqli_query($connection, "SELECT * FROM purchase_items WHERE item_id= ".$_GET['listItemName']"");
$row = mysqli_fetch_assoc($results);
{
$tb_qty=$row["avail_qty"];
}
if($tb_qty < $qty){ ?>
<script type="text/javascript">
alert("Quantity exceeds the stock limit");
</script>
<?php
}
?>
I tried a lot, but I couldn't fix this. Appreciate any help.

You should not print out html directly from an ajax call. You should echo out some json that you can parse on the front end to get the information. using
echo json_encode(['key' => 'value'])
here is your code, with a little modification. I added a dataType to the ajax query and a done function that is called when the ajax request has finished.
function checkQty() {
//Grab current forms input field values.
var txtQuantity = document.getElementById("txtQuantity").value;
var listItemName = document.getElementById("listItemName").value;
//Connect to database and verify Quantity Ordered isnt greater than Quantity In Stock.
$.ajax({
type: "POST",
url: "/pms/includes/functions/qty_check.php",
dataType: 'json',
data: {
listItemName: listItemName,
txtQuantity: txtQuantity
}
}).done(function(response){
alert('check your console!')
console.log('this is the response', response.available);
})
}
qty_check.php
<?php
error_reporting(E_ALL );
ini_set('display_errors', 1);
//Start the Session
if(!isset($_SESSION))
{
session_start();
}
include_once("../../config.php");
require __DIR__."../../dbutil.php";
if(!empty($_POST['txtQuantity'])){$qty = $_POST['txtQuantity'];}
if(!empty($_POST['listItemName'])){$item = $_POST['listItemName'];}
$results = mysqli_query($connection, "SELECT * FROM purchase_items WHERE item_id= ".$_GET['listItemName']"");
$row = mysqli_fetch_assoc($results);
{
$tb_qty=$row["avail_qty"];
}
// echo out some json to send to the front end
echo json_encode(['available' => $tb_qty < $qty]);
?>

Related

How to get the value of title image and content in ajax php

How to display the data title, image and content?
Here's the code:
view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$dataArr = array();
$responseArr = array();
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
array_push($dataArr, $data);
}
echo json_encode($dataArr);
}
mysqli_free_result($result);
} else {
echo "No Record";
}
}
index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
alert(data)
}
});
});
});
What I'm trying to do is to get the title, image and content.
How to get the value of title, image and content?
How to call the "title", "name" and "content" from the php?
console.log('DATA: ' + data);
No need to use while loop for result. Also remove extra $dataArr and $responseArr
Update your code to:
in view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
echo json_encode($data); exit;
}
mysqli_free_result($result);
}
}
$data['error'] = "No Record";
echo json_encode($data); exit;
Index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
var response = jQuery.parseJSON(data);
var title = response.title;
var name = response.name;
var content = response.content;
alert(title);
alert(name);
alert(content);
}
});
});
});
After taking data from jQuery side, you can set value in html side using id or class attribute in jQuery.
How your ajax receiving .php file should look:
$validLiteratureIds = ['yourTable1', 'yourTable2'];
if (!isset($_GET['edit_literature_id'], $_GET['literatureID']) || !in_array($_GET['literatureID'], $validLiteratureIds)) {
$response = ['error' => 'Missing/Invalid Data Submitted'];
} else {
$conn = new mysqli('localhost', 'root', '', 'dbname');
$sql = "SELECT title, name, content
FROM `{$_GET['literatureID']}`
WHERE `id` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_GET['edit_literature_id']);
$stmt->execute();
$stmt->bind_result($title, $name, $content);
if (!$stmt->fetch()) {
$response = ['error' => 'No Record'];
} else {
$response = [
'title'=> $title,
'name' => 'data:image/jpeg;base64,' . base64_encode($name),
'content' => $content
];
}
}
echo json_encode($response);
Important practices:
Validate the user input so that only qualifying submissions have the privilege of accessing your database.
Write the failure outcomes before success outcomes consistently throughout your project, this will make your scripts easier to read/follow.
Always use prepared statements and bind user-supplied data to placeholders into your query for stability/security.
The tablename cannot be bound like the id value; it must be written directly into your sql string -- this is why it is critical that you validate the value against a whitelist array of literature ids.
There is no need to declare new variables to receive the $_GET values; just access the values directly from the superglobal array.
I am going to assume that your id is a primary/unique key in your table(s), so you don't need to loop over your result set. Attempt to fetch one row -- it will either contain data or the result set was empty.
Call json_encode() only once and at the end of your script.
It is not worth clearing any results or closing a prepared statement or a connection, because those tasks are automatically done when the script execution is finished anyhow -- avoid the script bloat.
As for your jquery script:
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (response) {
if (response.hasOwnProperty('error')) {
console.log(response.error);
} else {
console.log(response.title, response.name, response.content);
}
}
});
});
});
I've trim away all of the irrelevant lines
changed POST to GET -- because you are merely reading data from the database, not writing
parseJSON() is not necessary -- response is a ready-to-use object.
I am checking for an error property in the response object so that the appropriate data is accessed.
Both scripts above are untested (and completely written from my phone). If I have made any typos, please leave me a comment and I'll fix it up.

How, Right Click a <tr>, run php to retrieve data, display result in an alert?

I've read and tried many solutions, none are working. Here is my latest. As you can see all I'm trying to do is display an alert box on screen with the data retrieved from the MySQL using PHP.
My HTML looks like this:
...
<td $brbCols class=\"editCS1\" oncontextmenu=\"getLastLogin('$row[callsign]');return false;\" id=\"callsign:$row[recordID]\" style=\'text-transform:uppercase\'> $row[callsign] </td>
...
Right clicking on the above code runs this,
The getLastLogin javascript looks like this:
function getLastLogin() {
$('tr').on('contextmenu', 'td', function(e) { //Get td under tr and invoke on contextmenu
e.preventDefault(); //Prevent defaults'
var idparm = $(this).attr('id');
var arparm = idparm.split(":");
var id = arparm[1];
id = id.replace(/\s+/g, '');
var call = $(this).html();
call = call.replace(/\s+/g, '');
$.ajax({
type: "GET",
url: "getLastLogIn.php",
data: {call : call, id : id},
success: function(response) {
alert(response);
},
error: function() {
alert('Not OKay');
}
});
});
}
The PHP:
<?php
ini_set('display_errors',1);
error_reporting (E_ALL ^ E_NOTICE);
require_once "creddtls.php";
$call = $_POST['call'];
$id = $_POST['id'];
$sql2 = "SELECT recordID, id, Fname, Lname, grid, creds,
email, latitude, longitude, tactical, callsign, logdate, netID, activity
FROM NetLog
WHERE callsign = '$call'
ORDER BY netID DESC
LIMIT 1,1 " ;
$stmt2 = $db_found->prepare($sql2);
$stmt2->execute();
$result = $stmt2->fetch();
$recordID = $result[0]; $email = $result[6];
$id = $result[1]; $latitude = $result[7];
$Fname = $result[2]; $longitude = $result[8];
$Lname = $result[3]; $creds = $result[5];
$tactical = $result[9]; $grid = $result[4];
$callsign = $result[10]; $netID = $result[12];
$logdate = $result[11]; $activity = $result[13];
$msg = "<b>Last Check-in::</b>
<br>$callsign, $Fname $Lname
<br><b>eMail::</b>$email
<br><b>Was on::</b> $logdate
<br><b>Net ID::</b> $netID, $activity
<br><br>
$recordID
";
echo "$msg";
?>
You are trying to access the data passed via ajax with the wrong superglobal.
You are looking at POST data, but your ajax call is using GET
Change $_POST to $_GET
Wrong or not the code writes to the lli DIV. So I added $("#lli").modal(); to the Javascript to open it in a modal dialog.
All is now well.

Passing JavaScript variable to PHP on dropdown change

I am trying to change text in a div depending on value change on a dropdown box. The dropdown box values are populated from MySQL using PHP. I am loading the dropdown box on page load.
<script>
$(document).ready(function() {
$('#products').change(function(){
var idval=$('#products').val();
$.ajax
( {
type: "post",
url: "my.php",
data: {winner_id:idval},
success: function(response)
{ alert("The winner was passed!")},
}
);
<?php
require_once 'config.php';
$iid=$_GET['winner_id'];
$sql="SELECT * FROM Products where prod_id = ".$iid;
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$prodCredit="Credit :".$row["prod_price"];
$time="estmated time is :".$row["prod_time"];
?>
$('#esdTime').text(' <?php echo $prodCredit ?> ' );
$('#credit').text(' <?php echo $time ?> ' );
});
});
</script>
I am not getting results.
Let me know how can I assign JavaScript value idval to PHP variable $iid value.
//you would want a the php script to be in a separate file that you could call Have the php file return an array or json object. Have the callback success function append the new options to the html select. The following is a ruffexample
<script>
$(document).ready(function() {
$('#products').change(function(){
var idval=$('#products').val();
$.ajax
( {
type: "post",
url: "my.php",
data: {winner_id:idval},
success: function(response){
for (var i = 0; i < response.length; i++) {
$("#idofyourselect").append("<option val='" +response[i]+"'>" + response[i] + "</option>");
}
},
}
);
</script>

Insert into MySQL through a Buttons OnClick

Using a few answers on here I have got row being added to MySQL upon a button press but the data is blank and so I can only assume the variables are not being passed.
I really don't know what I am doing wrong, any help would be greatly appreciated.
PHP
<? $sql = "SELECT itemname FROM items ORDER BY itemname ASC";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<button onclick='javascript:ajaxCall(" . $row['id'] . ")'><span class='btn-text'>" . $row['itemname'] . "</span></button>";
}
?>
jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function ajaxCall(id){
$.ajax({
type: "POST",
url: "additem.php",
success: function(data){
// callback function
}
});
return false;
}
</script>
additem.php
// Connect database.
include("settings.php");
mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_name);
$id = $_POST['id'];
$itemsearch = mysql_query("SELECT itemname, itemcategory, price, qty FROM presales WHERE id='$id'");
$itemsearchrest = mysql_num_rows($itemsearch);
$itemname = $itemsearchrest['itemname'];
$itemcategory = $itemsearchrest['itemcategory'];
$price = $itemsearchrest['price'];
$qty = $itemsearchrest['qty'];
$sql = "INSERT INTO presales (itemname, itemcategory, price, qty) VALUES('$itemname', '$itemcategory', '$price', '0')";
if(mysql_query($sql)){
return "success!";
}
else {
return "failed!";
}
?>
mysql_num_rows returns the number of rows. It's not an array. Use fetch_assoc or similiar.
See sample in the PHP documentation!
Also your AJAX call is missing the data:
$.ajax({
type: "POST",
url: "additem.php",
data: {
id: id
}
});
Please switch to PDO or MySQLi. MySQLi will use the same function names but it is object orientated. PDO will name the functions slightly different but basically work the same way.

Upvote button on website with JavaScript, Php, AJAX, MySql not working. What am I doing wrong?

I'm trying to create upvote/downvote buttons on a list of articles that I get from a MySql database. The buttons work in the sense that you press on the button and it gets the id of the article. However I can't get the id from article page to the php voting page. When I press the button the database doesn't register the vote. What am I doing wrong?
<script type="text/javascript">
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up')
{
alert('you upvoted on '+ dataString);
$(this).fadeIn(200);
$.ajax({
type: "POST",
url: "weblectureupvote.php",
data: dataString,
cache: false,
});
}
else
{
alert('you downvoted on '+ dataString);
$(this).fadeIn(200);
$.ajax({
type: "POST",
url: "weblectureupvote.php",
data: dataString,
cache: false,
});
}
return false;
});
});
</script>
This is the php file:
<?php
$pid = $_POST['id'];
try {
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result=mysql_query("SELECT * FROM database WHERE pid = '$pid' ") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
// temp user array
$lecturelist = array();
$lecturelist["pid"] = $row["pid"];
$lecturelist["upvote"] = $row["upvote"];
$lecturelist["downvote"] = $row["downvote"];
$lecturelist["vote"] = $row["vote"];
}
$upvote= $row["upvote"];
$downvote = $row["downvote"];
$vote = $row["vote"];
$upvote = $upvote + 1;
$query = $db->prepare('UPDATE database SET upvote = :upvote WHERE pid = :pid');
$query->execute(array(
':upvote' => $upvote,
':pid' => $pid
));
$query = $db->prepare('UPDATE database SET vote=:vote WHERE pid = :pid');
$query->execute(array(
':vote' => $vote,
':pid' => $pid
));
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
data: {id: id}
this will get to your php file a "id" variable ( this is the first id ) and with some value ( from the second id )
now
$pid = $_POST['id'];
this should work, as you weren't sending "much" to the server

Categories