Change price variable based on a dropdown selection with php and jquery - php

Problem: How can i get the selected price from a dropdown menu and use it instead of the original price of the current product stored in the database?
My approach: I've been able to update a label with the selected price, but I still need to override the current price of the product. I'm pretty clueless right now.
Additional information: The current price saved in the database is $price which need to be overridden by either $prijshalf or $prijsheel that are both also stored in the database.
The JQuery Code for updating the label:
<script type="text/javascript">
$(document).ready(function() {
$('.dropdown').change(function() {
var price = 0;
$('.dropdown').each(function() {
if($(this).val() != 0) {
price = parseFloat($(this).val());
}
});
$('#costLabel').text('€ ' + price.toFixed(2));
});
});
</script>
This code block gets the value of the selected dropdown menu item and puts it in the label #costLabel
The PHP Code for rendering the products:
$product_list = "";
while($row = mysql_fetch_array($results)){
$id = $row["id"];
$product_name = substr($row["product_name"],0,25);
$price = $row["price"];
$category = $row["category"];
$subcategory = $row["subcategory"];
$beschrijving = substr($row["details"],0,25);
$afbeelding = '<img src="inventory_images/' . $id . '.jpg" alt="' . $product_name . '" width="50" height="50" />';
$dropdown = $row["dropdown"];
$dropdown2 = $row["dropdown2"];
$prijshalf = $row["prijshalf"];
$prijsheel = $row["prijsheel"];
if($dropdown != "" || $dropdown2 != ""){
$dropdownshow = "<select name='dropdown' id='dropdown' class='dropdown'>
<option name='prijshalf' value='$prijshalf'>$dropdown</option>
<option name='prijsheel' value='$prijsheel'>$dropdown2</option>
</select>";
}
else{
$dropdownshow = "";
}
$product_list .= "<div class='produkt'>
<div class='hardlopers'>
$afbeelding
<div class='subinfo'>
<span class='prijs-info'>Prijs:</span><span class='prijs'><label id='costLabel' name='costLabel'>$price</label> </span>
<span class='productnaam'>$product_name</span>
<span class='dropdown'>
$dropdownshow
</span>
<form id='form1' name='form1' method='post' action='homepage.php#redirect'>
<input type='hidden' name='pid' id='pid' value='$id' />
<input type='submit' name='button' id='button' value='' />
</form>
<span class='info'></span>
</div>
</div>
</div>
";
}
// Prints out the products to screen
echo $product_list;

I can't see how is your process of adding an item to the cart, so i can't tell you how. But you can try to move the dropdown into the <form> tag, later with php you get the value and if it is prijshalf or prijsheel do the math. The same with js, put the selected value of the dropdown in a hidden input within the <form> if you doesn't want the dropdown into the <form>, but i don't see why it shouldn't, send it to the server and do the math there. All is up to you.
Always use js just to show the info, always do the calculation and validation with php in the server for security reasons.
Happy coding

Related

Populate dropdown based on checkbox

I have a form that contains a checkbox and a dropdown list. I use PHP to populate the dropdown list from two MySQL tables. Which table I use depends on whether the checkbox was checked or not. But, as you can see from my code sample, I can only populate that dropdown list after I submit the form. I want to be able to keep clicking on the checkbox and keep re-populating the dropdown list without having to submit the form. I am still new to this, so, please, give me as simple a solution as possible.
PS. I have a small bug in the code that doesn't keep the checkbox checked/unchecked after I submit the form. Working on fixing it.
Thank you
<?php
$Prc_Earn = 'Prc';
if (isset($_POST['submitBtn']))
{
if (isset($_POST['chkbox']))
{
$sql = 'select distinct Symbol from price_history.quarterly_earnings_history';
$Prc_Earn = 'Earn';
}
else
{
$sql = 'select distinct Symbol from price_history.stock_symbol_list';
$Prc_Earn = 'Prc';
}
}
// Connect to the database
include ('../Connections/mysql_connect.php');
if ($dbcon)
{
?>
<form method='post'>
<label for=''>Earnings / Prices</label>
<input type='checkbox' name='chkbox' id='chkbox' <?php if ($Prc_Earn == 'Prc') { echo "checked"; };?>><br><br>
<label for='symbol'>Stock Symbol:</label>
<select name = 'symbol' id='symbol'>
<?php
$result = mysqli_query($dbcon, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{ echo '<option value="' . $row['Symbol'] . '">' . $row['Symbol'] . '</option>'; }
}
?>
</select><br><br>
<button class='button' type='submit' name='submitBtn' id='submitBtn'>View Data</button><br><br>
</form>
<?php
}
?>

PHP - Populate form fields based upon <select> <option> value

I am trying to populate a form based upon the option selected in the <select>. The eventTitle field in the DB has corresponding fields located at the bottom of the code. If I select option 1, I want the form to be populated with the fields corresponding to option 1. I am not sure the best way to do this. Thanks in advance.
Also, if you have any other recommendations on things I should do differently, like if I am coding a bad practice, please advise. Thanks!
require_once "functions.php";
//this creates a reference to the connection which is in the functions.php file
$connection = getConnection();
//so far this gets all the event titles and echos out a drop down list with them in. yay
$sqlPopulateQuery = "SELECT eventTitle, eventID from NE_events";
$queryResult = $connection->query($sqlPopulateQuery);
echo "Event Title: <select name='eventTitle'>";
while ($record = $queryResult->fetchObject()) {
echo "<option value='{$record->eventTitle}'>{$record->eventTitle}</option>";
}
echo "</select>";
//if a specific event is selected
//get eventID from database
//populate textfield with eventID
//echo "Event ID: <input type='text' ' name='eventID' readonly><br>";
//echo "Venue ID: <input type='text' name='venueID'><br>";
//echo "Category ID: <input type='text' name='categoryID'><br>";
//echo "Start Date: <input type='date' name='eventStartDate'><br>";
//echo "End Date: <input type='date' name='eventEndDate'><br>";
//echo "Price: <input type='text' name='eventPrice'><br>";
?>```
You can achieve your requirement with either plain javascipt or with Jquery library, below I have listed each of the methods
1.Using javascript solution
<?php
while ($record = $queryResult->fetchObject()) {
echo "<option value='{$record->eventTitle}' onChange="popuplateData({$record->eventTitle})">{$record->eventTitle}</option>";
}
echo "Event ID: <input type='text' id='eventID' name='eventID' readonly><br>";
?>
<script>
function popuplateData(option){
if(option === 'title1'){ // For each option you can modify based on value
document.getElementById('eventID').value = 'event 1';
//More fields goes here
}
}
</script>
2.Using Jquery solution
<?php
echo "Event Title: <select name='eventTitle' id='eventTitle'>";
while ($record = $queryResult->fetchObject()) {
echo "<option value='{$record->eventTitle}'>{$record->eventTitle}</option>";
}
echo "</select>";
echo "Event ID: <input type='text' id='eventID' name='eventID' readonly><br>";
?>
<script>
jQuery(document).ready(function($) {
$("#eventTitle").change(function(){
var optionVal = $(this).val();
if(optionVal != ''){
if(optionVal === 'title1'){// For each option you can modify based on value
$('#eventID').val('event 1');
//More fields goes here
}
}
});
});
</script>

How can I pass the input box value on clicking anchor tag to php?

I want to pass the value for each rows to php page to update in database I am able to pass only id not the input box value
This is the table body
<?php
$cards = mysqli_query($con,"SELECT Username, Card_No, Card_Status FROM
smartcard WHERE Card_Status NOT IN (SELECT Card_Status FROM smartcard where Card_Status = 'Issued')");
?>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($cards))
{
echo '<tr>';
foreach ($row as $key => $value) {
echo '<td style="word-wrap: break-word;min-width: 10px;max-width: 300px;">',$value,'</td>';
}
echo '<td><form action="php/issue_card.php" method="POST"><input id="textbox" name="new_status" type="text" class="form-control" required="required"/></form></td>';
echo "<td>Status Update</button></td>";
echo '</tr>';
}
?>
</tbody>
This is the php page issue_card.php
<?php
include("connect.php");
$con = OpenCon();
$smartcard_no = $_GET['id'];
$admin_id = $_SESSION['Admin_Id'];
$new_status = $_POST['new_status'];
$sql = "UPDATE smartcard SET Card_Status = '$new_status', Admin_Id ='$admin_id' WHERE smartcard.smartcard_no = $smartcard_no";
mysqli_query($con, $sql);
CloseCon($con);
?>
For each row there will be different smartcard_no so I am using anchor tag to pass that directly using GET but not able to pass input box value.
<?php
$cards = mysqli_query($con,"SELECT Username, Card_No, Card_Status FROM
smartcard WHERE Card_Status NOT IN (SELECT Card_Status FROM smartcard where Card_Status = 'Issued')");
?>
<tbody>
<form>
<?php
while ($row = mysqli_fetch_assoc($cards))
{
echo '<tr>';
foreach ($row as $key => $value) {
echo '<td style="word-wrap: break-word;min-width: 10px;max-width: 300px;">',$value,'</td>';
}
echo '<td><input class="textbox" name="new_status" type="text" class="form-control" required="required"/></td>';
echo "<td><button class="updateBtn" data-id=".$row['Card_No'].">Status Update</button></a></td>";
echo '</tr>';
}
?>
</tbody>
<script>
/*import jquery before using this.*/
$(document).ready(function(){
$('.updateBtn').on('click',function(){
var status=$(this).parent().find('.textbox').val()
var id=$(this).attr('data-id');
sendData(status,id)
})
function sendData(status,id){
$.ajax({
url:'php/issue_card.php',
data:{status:status,id:id},
type:'get' //get or post,
success:function(success){
//callback
},
error:function(error){
//error callback
}
})
}
})
</script>
The following is a quickly written ( and not tested ) example of the 2nd idea - where there is just one form that encompasses the entire table and has two hidden fields for the important pieces of data that you wish to POST to the PHP script.
Each button within the table is assigned an event handler - the event handler in this case will query the DOM to find the text field within the same row and then assign that value and the value found in the buttons own data-id attribute o the hidden input fields before submitting the form.
<script>
document.addEventListener('DOMContentLoaded',function(e){
/* Obtain a reference to the FORM element */
var form=document.forms['status-updates'];
/* Hidden fields which will be POSTed to php/issue_card.php */
var id=form.querySelector('input[type="hidden"][name="id"]');
var status=form.querySelector('input[type="hidden"][name="new_status"]');
/* Create a nodelist collection of ALL buttons within table of class "bttn" */
var col=Array.prototype.slice.call( form.querySelectorAll('input[type="button"].bttn') );
/* Assign event handler to each button */
col.forEach( function( bttn ){
bttn.onclick=function(e){/* - event handler - */
/* Assign values to hidden fields */
id.value=this.dataset.id;
status.value=this.parentNode.querySelector('input[type="text"]').value;
/* submit the form with values for this row */
form.submit();
}.bind( bttn );
});
},false );
</script>
<form name='status-updates' method='post' action='php/issue_card.php'>
<!-- two hidden fields -->
<input type='hidden' name='id' />
<input type='hidden' name='new_status' />
<table>
<?php
while( $row = mysqli_fetch_assoc( $cards ) ) {
echo "
<tr>";
foreach( $row as $key => $value ) echo "
<td class='wrap'>{$value}</td>";
echo "
<td>
<input type='text' class='form-control' required='required' />
<input type='button' value='Status Update' class='bttn' data-id='{$row['Card_No']}' />
</td>
</tr>";
}
?>
</table>
</form>

Checked CheckBoxes

I need to store the ID of only the checked check boxes from the table of displaying products to use them in other things this is my code
while($row2 = mysql_fetch_array($result2)){
$pID= $row2[0];
$pName = $row2[1];
$pDes = $row2[2];
$pSale = $row2[5];
$pPrice = $row2[4];
$pPhoto = $row2[6];
if($counter % 4 == 0)echo "<tr> ";
echo "
<td> Name: '".$pName."' <br> ID: '".$pID."' <br> Price: '".$pPrice."' <br> <div id='parent'>
<img src='".$pPhoto."' width = '180' height = '180'/>
<br><input type='checkbox' name='item[]' value='".$pID."'" ." >
<div id='popup' >Description: ".$pDes." <br> Sale Percent: ".$pSale."
</div></div></td> ";
any help to mange how to store only the id of checked ckeckboxes (item[]) in array
If you are using form and want to get array of stored id when checkbox is checked after submitting the form. them no need to change the code it will select only checked checkbox values in array.
Without form we have to use jquery that answered by "Khaled Ouertani".

Fetching association with selected options in dropdown PHP CART

When i select a product in my gallery it goes to my cart.
I get my product id and store them in a session.
And in my cart i got to select size and which fabric i want to order my product.
My product is cushion.
My cart.php has all function to make the cart session work,
and has all the buttons functions too.
I display my selected products in my page checkout.php ... i call my cart function in that page...
To select size and fabric i have 2 dropdowns, the size dropdown is static html options, and my fabrics are getting data from my DB.
Look this image before...
As you see i got these two tables.
When i select my fabric and it size i want to fetch the value in the fabrics prices table.
My cart a got a session where it grabs the user state.
If the user is in the same state that i am,the price of the fabric will be one cost else it will be other cost.(IN_state,Out_state columns).
My QNTD row in the cart table is quantity $value
Valor is value of costs in pt-br.
A bad thing is that my dropdown dont save the selected option.
lets say that i selected a fabric Velvet and size 50x50.
And i click on add or less button my page will refresh and all options will be lost.
What i did is store the selected option using LocalStorage.
It works only for the first row in the checkout.
How can i get all these data to work with out submitting something.
Maybe i can use more sessions to get all data and make the calculation.
But im a bit lost in all this.
What can i do to get this working all together ?
my cart code..
<?php
include_once '../incluedes/conn_cms.php';
// gets the product id from gallery and store in session and add +1
if(isset($_GET['add'])){
$select = "SELECT * FROM gallery2 WHERE id=" . escape_string($_GET['add'])." ";
$run_selection = mysqli_query($conn,$select);
while($rows = mysqli_fetch_assoc($run_selection)){
if($rows['id'] != $_SESSION['product_'.$_GET['add']]){
$_SESSION['product_' . $_GET['add']]+=1;
header('Location: index.php');
}else{
$msg = "error";
header('Location: checkout.php');
}
}
}
//the plus button
if(isset($_GET['plus'])){
$_SESSION['product_'.$_GET['plus']]+=1;
if($_SESSION['product_'.$_GET['plus']] < 1){
header('Location: checkout.php');
}else{
header('Location: checkout.php');
}}
//the minus button
if(isset($_GET['remove'])){
$_SESSION['product_'.$_GET['remove']]--;
if($_SESSION['product_'.$_GET['remove']] < 1){
header('Location: checkout.php');
}else{
header('Location: checkout.php');
}
}
//the remove button
if(isset($_GET['delete'])){
$_SESSION['product_'.$_GET['delete']] = '0';
header('Location: checkout.php');
}
function cart(){
global $conn;
$fabric_options = '';
$query2 = "SELECT * FROM almofadas";
$result = mysqli_query($conn,$query2);
while($rows = mysqli_fetch_assoc($result)){
$fabric_options .= "<option value=''>{$rows['tecido']}</option>";
}
foreach ($_SESSION as $name => $value) {
if($value > 0){
if(substr($name, 0, 8 ) == "product_"){
$length = strlen($name) -8;
$item_id = substr($name,8 , $length);
$query = "SELECT *
FROM gallery2
WHERE gallery2.id =".escape_string($item_id). "";
$run_item = mysqli_query($conn,$query);
while($rows = mysqli_fetch_assoc($run_item)){
$vari = $rows['variante'];
$num = $rows['title'];
$id = $rows['id'];
$btn_add='<a class="btn btn-success" href="cart.php?plus='.$id.'"><i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i></a>';
$btn_remove = '<a class="btn btn-warning" href="cart.php?remove='.$id.'"><i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i></a>';
$btn_delete='<a class="btn btn-default delete_btn" href="cart.php?delete='.$id.'"><i class="fa fa-times fa-lg" aria-hidden="true"></i></a>';
if($rows['variante'] < 1){
$vari="";
}else{
$vari = "-".$rows['variante'];
}
$product = '
<td style="width:100px; "><img src="../'.$rows['image'].'" style="width:90%;border: 1px solid black;"></td>
<td>'.$num.''.$vari.'</td>
<td style="width:15%;">
<select id="fabric" class="form-control selectpicker" required="" >
'. $fabric_options . '
</select>
</td>
<td>
<select id="size" class="form-control selectpicker" required style="width:80%;" >
<option value="50">50x50</option>
<option value="45">45x45</option>
</select>
</td>
<td>'.$value.'</td>
<td>R$</td>
<td>sub.total</td>
<td>
'.$btn_add.' '.$btn_remove.' '.$btn_delete.'
</td>
</tr>';
echo $product;
}
}
}
}
}
My LocalStorage script in checkout.php
<script >
$(function() {
if (localStorage.getItem('fabric')) {
$("#fabric option").eq(localStorage.getItem('fabric')).prop('selected', true);
}
$("#fabric").on('change', function() {
localStorage.setItem('fabric', $('option:selected', this).index());
});
});
</script>
<script >
$(function() {
if (localStorage.getItem('size')) {
$("#size option").eq(localStorage.getItem('size')).prop('selected', true);
}
$("#size").on('change', function() {
localStorage.setItem('size', $('option:selected', this).index());
});
});
</script>

Categories