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

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 ~

Related

Using AJAX from another page to manipulate a database

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?

How do I resend a post request that has already been processed in php?

I see a lot of questions where people are trying to prevent a POST request from being resent, but I want the opposite. I want to have a retry button that resends the POST data that has already been sent.
In Chrome, when I manually refresh the page the POST request is resend when I choose OK on the warning. However, when I try to replicate this by making a button that refreshes the page it does so without the original POST data.
edit: forgot to mention why I'm doing this.
The reason I want to do this is because this is a random choice generator. You put in a list of choices on the index page, and then a random one is bolded on the process.php page when you submit the form. However, I see no need to store this information in SQL or anything, I just want there to be a simple "retry" button so that they can get another try at it in case they didn't like the results.
Here's the php:
<?php
$name = $_POST["titleChoice"];
if (sizeof($_POST["choice"]) != 0){
$randomNumber = rand(1, sizeof($_POST["choice"]));
echo "<b>" . $name . "</b><br><br>";
for ($i = 1; $i <= sizeof($_POST["choice"]); $i++) {
if ($randomNumber == $i){
echo "<b>" . $i . ". " . $_POST["choice"][$i-1] . "</b><br>";
}
else{
echo $i . ". " . $_POST["choice"][$i-1] . "<br>";
}
}
}
else{
echo "No choices were inputted! Would you like to try again?";
}
?>
And here's the retry button:
<form action="process.php" method="post">
<button name="submit" class="btn-lg" onclick="reloadPage();"> Retry </button>
</form>
<script type="text/javascript">
function reloadPage()
{
window.location.reload();
}
</script>
I'm new to PHP so any help would be appreciated, thanks!
Nevermind, I realized I made a stupid mistake.
I originally had the button as a form like this:
<form action="process.php" method="post">
<button name="submit" class="btn-lg" onclick="reloadPage();"> Retry </button>
</form>
but it should just be a button:
<button name="submit" class="btn-lg" onclick="reloadPage();"> Retry </button>

Php echo onClick JS Function (pass string):: Uncaught SyntaxError: Unexpected token

Using simple PHP and Javascripet (no JSON, AJAX, or anything fancy) I am trying to echo a javascript onClick event function. This onClick function takes two strings, and as a start I want to see those strings using the "alert" function. Below is my code in the html/php file::
<DIV id="show">
!-- few more lines here -->
<?PHP
$CONN = mysqli_connect($SERVER_w, $USER_w, $PASS_w, $DBNAME_w);
$SQL = "SELECT * from COUNTRYTABLE";
$RESULT = mysqli_query($CONN, $SQL);
$NUM_RECORDS = mysqli_num_rows($RESULT);
echo "<BR>";
for($x = 1; $x<=$NUM_RECORDS; $x++)
{ $ROW = mysqli_fetch_array($RESULT, MYSQLI_ASSOC);
//the main line::
echo "<button onClick=\"Show_Pair(\"" . $ROW['CONTINENT'] . "\",\"" .
$ROW['COUNTRY'] . "\")\"> Show! </button> <BR>";
}
mysqli_free_result($RESULT);
mysqli_close($CONN);
?>
</DIV>
The Javascript function is a simple one:
function Show_Pair_In_Alert(CON, CTR)
{
alert(CON + CTR);
}
When the PHP evaluates, the HTML looks like follows:
<DIV id="show">
<p>CONTINENT - COUNTRY Linkage: </p><BR><BR><button
onClick="Show_Pair_In_Alert("AFRICA_EAST","Comoros")">Show</button> <BR>
<button onClick="Show_Pair_In_Alert("AFRICA_EAST","Eritrea")">Show</button>
<BR>
<button onClick="Show_Pair_In_Alert("AFRICA_EAST","Kenya")">Show</button>
<BR>
</DIV>
HOWEVER, when I look at the developer tools/console thingy in Chrome, I see the following error::
Uncaught SyntaxError: Unexpected token }, and this error occurrs just above the end of the and below the last button.. theres a red circle with a yellow cross in it.. as can be seen in the image below
Would appreciate any feedback.. just to reiterate.. im not using any JSON, AJAX, anything... just trying to achieve something fairly complex for my begineer level :P.. thank you very much for your assistance in advance!!

simple-gallery.js only partially working, js conflict?

I am using simple-gallery.js (found here: alexkalicki.com/jquery-simple-gallery/) and it is only half-way working for me. The script seems to be pulling in the photos per the jQuery initiation code, but clicking on the thumbnails does not replace the large photo (.project-image) the way it is suppose to. I have gotten the same plugin working before, I assume there must be some kind of javascript conflict or a dumb coding mistake I can't see. Any help would be much appreciated.
The test site is here: joshofsorts.com/projects/dsenergy/#commercial. If you click on one of the photos under the "Portfolio" heading, it will reveal the gallery in question.
Here is my js that is dynamically creating the initiation jQuery line for each gallery and inserting it into the footer:
var newjava = "<scr"+"ipt type='text/javascript'>";
newjava += "jQuery(document).ready(function($) {";
$('[id$=-project-gallery]').each(function() {
var the_id = this.id;
newjava += "$('#" + the_id + " .project-image').gallery({source:'#" + the_id + " .project-thumbnails img'});";
});
newjava += "});";
newjava += "</scr"+"ipt>";
$('#newjava').replaceWith(newjava);
And here is the html/php:
<div id="<?php echo $solution; ?><?php echo $item; ?>-project-gallery">
<div class="project-image"></div>
<div class="project-thumbnails"
<?php if($image_count == 1){echo ' style="display:none"';} ?>>
<?php $fourmax=0;
foreach ($images as $image){
if($fourmax==4) break;
echo '<img src='.$image['sizes']['project-image'].'>';
$fourmax++;
} ?>
</div>
</div>

Delete specific uploaded file from folder on server and display remaining files

going a bit crazy trying to get this to work... I have a photo upload page that lets you upload multiple photos and displays all the uploaded photos of a specific user below the upload form. I also place a delete button next to each photo however once you delete a photo it keeps displaying that image (although with a broken link as the photo is deleted from the server). I start by looping through a table that holds the file dir and name and then displays those photos. I have a submit button that calls the unlink() function.
$photoQuery= "SELECT * FROM photo_index WHERE User_ID='$UserID'";
$result = mysqli_query($dbcon, $photoQuery);
while ($photo_data = mysqli_fetch_array($result)){
echo "<form id=photo_Form action=listing_photos.php method=post> ";
echo "<input type=hidden name=photoDir value='$photo_data[Photo_Dir]' />";
echo "<input type=submit name=photoDel id=submit_but value=Delete />";
echo "</form>";
echo "<img src='$photo_data[Photo_Dir]' height=100px width=100px>";
}
Then here is the php that deletes the photo file and the row in the table that stored the photo info.
if (isset($_POST['photoDel'])){
$fh = fopen($_POST['photoDir'], 'a');
fclose($fh);
unlink($_POST['photoDir']);
$photoDel= "DELETE FROM photo_index WHERE Photo_Dir='$_POST[photoDir]'";
$result = mysqli_query($dbcon, $photoDel) or die(mysql_error());
echo "Photo Removed";
}
I had to open and close the file before using unlink because if I didnt I would always get a warning after the photo was deleted saying that unlink(images/somephoto.jpg) did not exist (because it had been removed from the server already)
Once the delete button is clicked it should refresh the page shouldn't it?? and when the page refreshes it should reload the query and only display the photos that are listed in the photo tabel?? For what ever reason it takes two refreshes to get that result. Any help would be very much appreciated, or any way to just do this better! Cheers.
First off, your code is vulnerable to SQL injection. You should look into that. Next, maybe you should use JS to find and remove the image from the document. So, have a <button> that runs a function which removes the image with that specific source from the document.
Here's a PHP snippet:
$photoQuery= "SELECT * FROM photo_index WHERE User_ID='$UserID'";
$result = mysqli_query($dbcon, $photoQuery);
while ($photo_data = mysqli_fetch_array($result)){
echo "<form id=photo_Form action=listing_photos.php method=post> ";
echo "<input type=hidden name=photoDir value=". $photo_data[Photo_Dir] . "/>";
echo "<input type=submit name=photoDel id=submit_but value=Delete />";
echo "</form>";
echo "<img src=" .$photo_data[Photo_Dir]. " id = 'picture' height=100px width=100px>";
echo "<script>
var d = getElementById('submit_but');
var b = getElementById('pic');
d.onclick = function(){
pic.parentNode.removeChild(b);
return true;
}
</script>";
}
See here for the JavaScript:
http://jsfiddle.net/BUXBq/

Categories

Resources