Using AJAX from another page to manipulate a database - javascript

I am building a warranty product website as a side project for a small business I work at (We deal with batteries for cars, heavy equipment...). There is a lot going on here.
Basically, when an item gets returned for a warranty inspection the user can input the customer's information and the product information for it to be tracked and managed. I began with making a database in PHP (It is only one table and not fully normalized since it really does not need to be unless there is expansion later on) with only one table that manages transactions.
Each transaction when submitted defaults to ACTIVE status meaning it can be manipulated (Deleted, resolved, or to add a comment) via buttons in the table. To be able to do this I have been using AJAX to be able to use buttons in a table and change the Status to DELETED or RESOLVED.
Now, there are four pages of tables (Like ALL, ACTIVE, DELETED, and RESOLVED) and each ran a very similar code (While loop that displayed the table) with the expectation of the SQL statement. For example the ALL inspections table has nowhere clause in the SQL statement, while the ACTIVE Inspections table would have a where Status = "ACTIVE", as so on for resolved and deleted. Since displaying the data seemed repetitive to have a while loop, I decided to make one table.php page with a function call GetTableData and on each page (ACTIVE, ALL, DELETED...) I would include the PHP file, and then call and pass through the SQL statement, like so...
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Battery Wholesale Inspection Database</title>
</head>
<?php include 'headernNavbar.html'; include 'Actions/connection.php'; include 'Actions/table.php'?>
<body>
<h1 id="title">Active Inspection Database</h1>
</body>
</html>
<?php
$sql = "SELECT TransactionID, CustomerName, PhoneNumber, ReceivedDate, Item, DATE_FORMAT(ManufactureDate, '%m-%y') as Age , InitalVoltage, InitalCCA, Comments, WarrStatus FROM inspection.product WHERE product.WarrStatus = 'ACTIVE' ORDER BY ReceivedDate DESC";
GetTableData($sql, $conn);
?>
Here is what the table.php file looks like...
<html>
<head>
<title></title>
</head>
<?php
include 'Actions/connection.php';
function GetTableData($sql, $conn){
$result = mysqli_query($conn, $sql);
echo "<table id='inspectTable' class='inspectTable'>";
echo "<thead><tr>";
echo "<th>Customer</th>";
echo "<th>Phone</th>";
echo "<th>Received</th>";
echo "<th>Item</th>";
echo "<th>Age</th>";
echo "<th>Voltage</th>";
echo "<th>CCA/AH</th>";
echo "<th>Comments</th>";
echo "<th>Status</th>";
echo "<th colspan=3 >Tools</th>";
echo "</thead></tr>";
if (mysqli_num_rows($result) > 0) {
// output data of each row
echo "<tbody class='dbTable'>";
while($row = mysqli_fetch_assoc($result)) {
$id= $row['TransactionID'];
echo "
<tr><td>" . $row['CustomerName'] ."</td>
<td>" . $row['PhoneNumber'] . "</td>
<td>" . $row['ReceivedDate'] . "</td>
<td>" . $row['Item'] . "</td>
<td>" . $row['Age'] . "</td>
<td>" . $row['InitalVoltage'] . "</td>
<td>" . $row['InitalCCA'] . "</td>
<td>" . $row['Comments'] ."</td>
<td>" . $row['WarrStatus'] ."</td>";
if ($row['WarrStatus'] == 'ACTIVE'){
echo "<td><button class='deleteRow' id='".$id."' >Delete</button></td>
<td><button class='updateRow' id='".$id."' >Update</button></td>
<td><button class='resolveRow' id='".$id."' >Resolve</button></td>";
}
else{
echo "<td><button class='deleteRow' id='".$id."' disabled >Delete</button></td>
<td><button class='updateRow' id='".$id."'disabled >Update</button></td>
<td><button class='resolveRow' id='".$id."'disabled>Resolve</button></td>";
}
}
echo "</tbody>";
} else {
echo "Not Data Avaibable.";
}
}
?>
<script>
$(".deleteRow").click(function()
{
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'Action/deleteAction.php',
data:'id='+del_id,
success: function(data)
{
location.reload();
}
});
});
$(".resolveRow").click(function()
{
var del_id = $(this).attr('id');2
$.ajax({
type:'POST',
url:'resolveAction.php',
data:'id='+del_id,
success: function(data)
{
location.reload();
}
});
});
</script>
</html>
So, as an example when the user is on the ACTIVE inspections page, and the list gets called it is displayed. When the user wants to delete an entery and clicked delete, the deleteAction.php should be called and changes the status from ACTIVE to DELETE. Here is the php for that...
<html>
<head>
<title>delete action</title>
</head>
<?php include 'connection.php'?>
<?php
$id = $_POST['id'];
$sql = "UPDATE inspection.product
SET DeletedDate = now(), WarrStatus = 'DELETED'
WHERE TransactionID = $id";
mysqli_query($conn,$sql);
?>
</html>
Now here is the problem I am facing. When a button (For example the delete button) is clicked nothing changes. Unlike when I first had the while loop (in the table.php) on each page with the AJAX js stuff it worked like a charm. I am just not sure if I am missing something. Here are the things I have tried:
Had each while loop and SQL statement in each PHP page with the AJAX
Created a separate js file and referenced that in the table.php, as well as each PHP page
Only had the AJAX js stuff in the other pages but still called the GetTableData
I have also not accomplished the updating comment button as of yet
Could anyone let a hand here? I would greatly appreciate it! If you see any other things I should do to improve I would also appreciate that. This is my first web project out of the first year!
EDIT:
I also forgot to include that reference to ajax in the table.php, it is there on my system, but I was playing around and forgot to add it in the post! This didn't fix the issue.
EDIT:
So after playing around with it, it does work when putting the ajax js in each php file, however it does not work when I have a separate js file and including that into each php file. Is there a different way to do this for it is a little cleaner?

Related

Update db data without losing collapsed rows

Sorry for being dumb, I'm quite new to PHP.
I have a table filled with data from a database:
machine.php
<?php require "database.php"; // here the connection stuff
const DOT_ONLINE = "🟢";
const DOT_OFFLINE = "🔴";
?>
<table id="tableMachines" class="table table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">Online</th>
<th scope="col">Name</th>
<th scope="col">Type</th>
<th scope="col">Address</th>
</tr>
</thead>
<tbody>
<?php
try {
$stmt = $db->prepare("SELECT * FROM machines ORDER BY address;");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_OBJ);
foreach ($stmt->fetchAll() as $row) {
$rowId = "row" . $row->name;
$output = "<tr data-bs-toggle='collapse' data-bs-target='#$rowId'>"
. "<td>" . ($row->online ? DOT_ONLINE : DOT_OFFLINE) . "</td>"
. "<td>" . $row->name . "</td>"
. "<td>" . $row->type . "</td>"
. "<td>" . $row->address . "</td>"
."</tr>";
echo $output;
$output = "<tr id='" . $rowId . "' class='collapse fade'>"
."<td colspan='4'>"
."<table class='table table-borderless'>"
."<tr><td>Order: " . $row->job . "</td></tr>"
."<tr><td>Length: " . $row->length . "</td></tr>"
."</table>"
."</td>"
."</tr>";
echo $output;
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
</tbody>
</table>
<?php
$db = null;
As you can see, the user can click on each row to show some further details.
In the main page I put the above file inside a div:
<div id="tableMachines">
<?php require 'machines.php' ?>
</div>
Periodically I fetch new data:
$(document).ready(function() {
setInterval(function () {
$('#tableMachines').load('machines.php');
}, 5000);
});
It works fine, the problem is when the div reloads I lose the rows that were shown by the user.
It's true I can keep track of which rows were expanded and manually trigger them again after reloading the PHP code, but I don't think this is the correct approach.
Would you mind to help me to understand how to update the data without interfere with the UI?
If this were me, I would track which last machine ID is pulled through and then send that on your load() call. You can then call $('#tableMachines').prepend(data) rather than reloading the whole table - you only reload the latest rows. That way your users choices will be unaffected however you may need to re-bind click/triggers so the new rows expand/hide as well.
Before loading machine.php, you can create a cookie named "expanded_set" in your jquery code that loads machine.php. Each time visitor toggles, you can populate the cookie. In machine.php file, your cookie will be accessible by $_COOKIE['user_expandeds']. Then you can customize machine.php to handle the already-toggled ones to show them also.
I'm not sure of this method for timing issues however, you may also send the "expanded_set" to PHP via a POST type form with a hidden input field with a name which is submitted by jquery automatically also. You can access the posted field with its name as $_POST['expanded_set'].
cookie method may fail if cookies are not allowed by the visitor but using a form method can not be disallowed.

Execute AJAX from Main file after previously inserting data through AJAX

I have a questions for which I need some help.
I have a page which, after it is finished loading, executes an AJAX, creates a table in PHP containing 2 buttons: 1 change password, the other is delete. Once the table is complete it is injected into a div in the main file. That works great so far. Now after that table is loaded, I want to be able to call another AJAX function linked in the JS file in the main page. So I have 3 components:
1. <div id="DbInfo"></div>
That is where I add the information from the users.
my php which executes the code and gets the information from my database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT LoginName FROM table";
$res = mysqli_query($conn, $sql);
if (mysqli_num_rows($res) > 0) {echo "<center>";
echo "<table border='1'>";
echo "<tr>";
echo "<td>User</td>";
echo "<td colspan=2 align=center>Available Functions</td>";
echo "</tr>";
while($row = mysqli_fetch_assoc($res)) {
echo "<tr>";
echo "<td>" . $row['User'] . "</td>";
echo "<td><button type='button' class='smallbutton' id='removeUser' value='" . $row['LoginName'] . "'>Delete User</button></td>";
echo "<td><button type='button' class='smallbutton' id='CPW' value='" . $row['LoginName'] . "'>Change Password</button></td>";
echo "</tr>";
}
echo "</table>";
echo "</center>";
} else {
echo "";
}
mysqli_close($conn);
And lastly the AJAX which does the injection of the created table into the HTML:
$(document).ready(function(){
$.ajax({
method: "POST",
url: "UserData.php",
success: function(data){
//document.getElementById("DbInfo").innerHTML = data;
document.getElementById("DbInfo").html(data);
}
});
});
Again, these functions are working fine. What I want to do after the page is done, be able to click one of these injected buttons and execute another AJAX. Unfortunately the standard declaration that I use for AJAX does not work.
$(document).ready(function(){
$("#removeUser").click(function(){
The question: How can I make sure after the table is injected, that I can call an AJAX function which is linked as an external source (<script src="script.js"></script>) in the main document?
Thanks for your help.
try :
$('#DbInfo').on('click', 'button[id="removeUser"]', function(i,e){
console.log('remove :' + $(this).val());
});

Updating MySQL Database with checkboxes and PHP

I am trying to update a MySQL database with checkboxes and PHP. I have read a lot of code examples online and read many questions on here but I seem to be stuck at the last hurdle.
My code first queries MySQL to bring back a list of users and then a checkbox (which is either 0 or 1 in MySQL) next to each one, indicating whether or not the user is completed.
What I am wanting to do is when the checkbox is checked, for that to update the MySQL database and update the column with 1, or if it is unchecked, for it to change the column to 2.
Here is my code so far:
HTML Snippet (Checkboxes):
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Firstname'] . "</td>";
echo "<td>" . $row['Surname'] . "</td>";
echo "<td>" . $row['Department'] . "</td>";
echo "<td>" . $row['RequestedBy'] . "</td>";
echo "<td>" . $row['StartDate'] . "</td>";
echo "<td class='tbl-chk'> <input type='checkbox' name='WSCompleted' value='"; echo $row['ID'] . "'" ; if ($row['WSCompleted']=='1') { echo "checked='checked'";} echo "/></td>";
Here is my jQuery that successfully retrieves the values and IDs and then posts them:
$(document).ready(function(){
$('input[name=WSCompleted]').click(function(){
var wsCompleted = $(this).is(':checked') ? 1 : 0;
var wsCompletedID = $(this).attr('value');
$.ajax({
type: "POST",
url: "/usr-handler.php",
data: {id: wsCompletedID, wsCompleted: wsCompleted},
success: function(){
$('div.success').fadeIn();
}
});
return true;
});
});
And finally here is a snippet of my PHP:
$wsCompleted = $_POST['wsCompleted'];
$id = $_POST['wsCompletedID'];
$query = "UPDATE newusers SET WSCompleted = '$wsCompleted' WHERE id = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
I am setting the value of the checkbox to what is actually the row ID in MySQL, then I can use the checkbox value to select the correct row in MySQL, and update it.
The problem I am having is that currently, how the code is, I get the following response from FireBug:
Unidentified index: WSCompletedID
After looking online it was suggested to change:
$id = $_POST['wsCompletedID'];
To:
$id = (ISSET($_POST['wsCompletedID']));
But doing so clears the error message, but then doesn't actually update the value on MySQL.
If I manually set the $id to something, the update works, but obviously that isn't right as it would only ever update the ID I have chosen it to.
I am completely stumped as to what is causing the problem. I have tried finding out online but cannot get anywhere with it.
Any help is greatly appreciated.
Thank you
You are loading data here in your javascript AJAX code
data: {id: wsCompletedID, wsCompleted: wsCompleted},
This will create the following $_POST array
id => whatever was in wsCompletedID
wsCompleted => whatever was in wsCompleted
So your PHP code should be looking for $_POST['id'] and $_POST['wsCompleted'] as these are the names you have given in your data:...
$wsCompleted = $_POST['wsCompleted'];
$id = $_POST['id'];
$query = "UPDATE newusers SET WSCompleted = '$wsCompleted' WHERE id = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
HOWEVER: Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared statement and parameterized statements

Is it possible to combine javascript/jquery and mysql/php

I have a odd question i cannot find the answer to, which probably means it is impossible. The reason i ask is i am creating a food delivery website. In the admin panel of my website administers are able to input restaurant details and menus. Part of the details is how much a customer must spend before they can checkout for delivery. so i want to be able to deactivate the checkout button, but when they met the minimum order fee the button activates.
This is my first time attempting anything like this, i have looked all over and i can only find posts or tutorials on how to deactivate then activate a button when a certain event takes place using javascript or jQuery and i know i would have to get the minimum order fee from the DB.
The only logical answer is to combine them.
I am trying to achieve something similar to this...
Shopping
I followed a tutorial to do this, it is a mini fixed shopping cart, which is on the same page as the shopping cart. It redirects to shopping_cart.php from product_page.php. Most aspects on product_page.php is dynamically made.
mysqli_stmt_execute($runn_query);
while ($get_row = mysqli_fetch_array($runn_query)) {
echo "<div id='prods_ere'>";
$item_sub = $get_row['Product_Price'] * $value;
echo $value . ' x ' .$get_row['Product_Name']. ' # £' . $get_row['Product_Price'] . '<a id="minus" class="buttons" href="Shopping_cart.php?remove=' . $Product_Id . '">-</a> <a id="plus" class="buttons" href="Shopping_cart.php?add_item=' . $Product_Id . '"> + </a> <a id="del" class="buttons" href="Shopping_cart.php?delete=' . $Product_Id . '">✖</a> </br><p id="sub">£' . $item_sub . '</p>';
echo "<br>";
echo "<br>";
echo "<hr id='shopp_dashed'>";
echo "</div>";
}
}
//creating subtotal
$sub_total += $item_sub;
$num_items += $value;
$total += $sub_total;
}
}
//subtotal and empty cart message
if ($sub_total == 0) {
echo "Ouch.. its empty in here";
} else {
echo "<div id='grey'>";
echo"Subtotal (excl delivery)";
echo "<br/>";
echo "<div id='sub_t'>";
echo '£' . number_format($sub_total, 2);
echo "</div>";
echo "<br/>";
echo"Items";
echo "<br/>";
echo "$num_items";
echo "<br/>";
echo "</div>";
echo "<div id='total'>";
echo"Total: ";
echo "$total";
echo "</div>";
}
Products page
<div id="prods_here">
<!-- PLACE PRODUCTS HERE-->
<?php cart(); ?>
</div>
Well, I'm not sure how you're keeping track of the customer's order but let's say you're keep track of it in a counter, say, totalOrderAmt. As they are making changes to the order, keep this updated and add a condition to the page, that when the totalOrderAmt >= checkOutAmt, enable the checkOut button.
I can add more details if you post some code, may be.
If you're using PHP you could load a JavaScript object on each restaurant page that basically makes a minimum_order_price variable available on the DOM for the JavaScript to handle the rest:
<html>
<head>
...
</head>
<body>
<h1>Restaurant X</h1>
<p>Minimum order: <span id="_restaurantMinimumOrder"></span></p>
<input id="submit" type="submit" class="disabled" value="Checkout" disabled>
<script type="text/javascript">
<?php
echo "window.RestaurantDetails = {}";
echo "window.RestaurantDetails.minimum = $RestaurantMinimumOrder";
?>
</script>
</body>
</html>
In this instance, $RestaurantMinimumOrder is something you configure and setup on PHP (I am not sure what you're setup is so I went with a variable name). From there, when the page is parsed from the server, the PHP will echo out that JavaScript. Once the page loads, window.RestaurantDetails will be available for the rest of your JavaScript to use. I've also included an example implementation:
<script type="text/javascript">
// set price on the DOM
var priceEl = document.getElementById('_restaurantMinimumOrder');
priceEl.textContent = window.RestaurantDetails.minimum;
// ensure submit button is disabled initially
var submitEl = document.getElementById('submit');
submitEl.disabled = true;
</script>
From here, if you're using jQuery you can easily adjust the state of the submit button based on whatever logic flow you have setup. Let me know if you have more questions. Best of luck! Cheers ~

Delete specific entry from database by clicking on it

I'm building a web App for a friend, this is my first async site and I'm learning lots of cool stuff, but there are some details that make me struggle.
This is the general idea:
This simple app gets specific tables from a database using PHP and jQuery and shows them asynchronously on the page. There's this specific table (a waitlist) that shows all atributes from all entries on the table plus a small button that SHOULD delete that specific entry, the PHP code for the creation of the table is as follows:
<?php
include("con.php");
$result = mysqli_query($c,"SELECT * FROM waitlist");
echo "<thead>";
echo "<tr>";
echo "<th>Nombre</th><th>Sillas</th><th>Hora de Llegada</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['CHAIRS']."</td>";
echo "<td>". $places ['CREATED']."</td>";
echo '<td>
<button class="btn btn-default" type="submit" name=' . $places ['ID'] . ' id="deleteWaitlist">X</button>
</td>';
echo "</tr>";
}
echo "</tbody>";
mysqli_free_result($result);
?>
This is the table schema:
CREATE TABLE WAITLIST (
ID MEDIUMINT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255),
CHAIRS VARCHAR(255),
CREATED DATETIME NOT NULL,
PRIMARY KEY(ID)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
What is the best way of having the button delete the entry it apears on? The function refreshes the table every few seconds so deleting it from the database is all I need. I also have an incomplete PHP function that gets called on buttonpress that shold delete the entry, but Im unsure as to how to complete it. Here it is:
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
mysqli_query($c,$sql);
?>
I need to replace the $_POST[name] with an identifier for the row, this is my problem. What's the best way of doing this? Can I pass it somehow though the jquery.ajax() call? Do I need a new table attribute ID? I'm sure the "this" keyword can be used somewhere. Is PHP and ajax even the best way of doing it?
Ajax writes the table on "#result_table", here's the relevant code if it's needed:
<div class="row">
<div class="col-lg-12" id="table_container">
<table class="table table-striped" id="result_table">
</table>
</div>
</div>
</div>
EDIT: I updated the code as recomended by #vnponce
This is the code for the ajax call:
$("#deleteWaitlist").click(function(){
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({
url: 'deleteWaitlist.php',
data: { id : i},
success: function(result){
// do some code here
// here yo can see 'result' response of YOUR_PHP_FILE
console.log(result);
}
});
});
After fiddling with the code I got rid of all errors and updated the post, but the entries are still not getting deleted.
The best way is creating an ID identifier in your table, then this identifier can be added in your 'Delete' button.
The button trigger a function that send ID, and your PHP file recive it and delete de data comparing the ID.
The identifier can be added in table schema ( i don't know if it is the rigth code, I always made in phpMyAdmin )
CREATE TABLE WAITLIST (
ID MEDIUMINT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255),
CHAIRS VARCHAR(255),
CREATED DATETIME NOT NULL
);
First add the ID in delete photo.
echo '<td>
<button class="btn btn-default" type="submit" name=' . $places ['ID']. ' "id="deleteWaitlist">X</button>
</td>';
The ajax
$("#deleteWaitlist").click(function(){
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({url: "YOUR_PHP_FILE.php", {id: i}, success: function(result){
// do some code here
// here yo can see 'result' response of YOUR_PHP_FILE
// console.log(result);
}});
});
Now your PHP with ID
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
mysqli_query($c,$sql);
?>
Well I hope help. If i have an error or you have a question let me know.
UPDATE*
Maybe there's an error deleteWaitlist.php , you can return error if it exist.
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
if ( ! mysqli_query($c,$sql) )
{
return "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Categories

Resources