How to change quantity with php and plausible js? - javascript

Okay so I have this problem on a site im working om.. some merchandise that have been selected are POST'ed from a form to this page. Then the prices are gathered from the db and it all gets added to get the total sum price.. However I need to get a function where you can change the quantity of the items selected.
The code I have so far is this - For displaying the selected products.
$t_id=implode(',',$t_id);//impload the value with the ',' and used IN operate to get all the value relate this id (11, 19 and 20)
$query = "SELECT * FROM tilbehor WHERE t_id IN ($t_id)";
$result = $db->query($query);
$num_rows = $result->num_rows;
if($num_rows > 0) {
while($row = mysqli_fetch_array($result)) {
echo "
∙ <input type='text' style='width: 50px;' name='quantity' id='quantity' class='txt' value='1'> - <b>".$row['tilbehor_navn']."</b><br>
";
}
} else {
echo "Error";
}
And here is the code to display and add up alle the prices.
$test = $_POST['tilbehor'];
$test=implode(',',$test);//impload the value with the ',' and used IN operate to get all the value relate this id (11, 19 and 20)
$query = "SELECT * FROM tilbehor WHERE t_id IN ($test)";
$result = $db->query($query);
$num_rows = $result->num_rows;
if($num_rows > 0) {
$number = $p_pris + $o_tilbehor_pris;
while ($row = mysqli_fetch_array($result)) {
$number += $row['kunde_pris'];
}
$output = $number;
$followers = number_format( $output , 0 , '.' , '.' );
echo "
<br>
<input type='checkbox' name='price' value='$followers'>Kunde pris $followers<br>
";
} else {
$number = $p_pris + $o_tilbehor_pris;
$output = $number;
$followers = number_format( $output , 0 , '.' , '.' );
echo $followers;
echo ",-";
}
Anyone have any idea on how to code it so you can change the quantity of an item and so that the price is affected as well? :)

Related

How do I set the value of an option into a variable without submit button?

I am working on pagination ,
I have created a table, in which initial limit is placed as 5 that 5 table rows will show in page , I have made a dropdown in which there are five option are provided to choose 5,10,15,20,25 options. Now I want to show table rows data according to select option , like if I select 5 then the data show only 5 rows , if I select 10 then table shows 10 rows data and same for 25 .
I have predefined limit value which is 5 , but How do I set the value of an option into this limit variable without submit button ?
<?php
$sql12 = "SELECT numbers FROM pagenumber";
$result12 = mysqli_query($conn,$sql12);
echo "<select name='username'>";
while ($row12 = mysqli_fetch_array($result12)) {
echo "<option value='" . $row12['numbers'] ."'>" . $row12['numbers'] ."</option>";
}
echo "</select>";
$limit = 5;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $limit;
$sql="SELECT * FROM invoice_details WHERE userid='$userid' ORDER BY invoice_no DESC LIMIT $start_from, $limit";
$result=mysqli_query($conn,$sql);
$row=mysqli_num_rows($result);
$table_data = '';
if($result){
while($row = mysqli_fetch_assoc($result)){
$invoice_no = $row['invoice_no'];
$customer_id = $row['customer_id'];
$start_date = $row['start_date'];
$end_date = $row['end_date'];
$paystatus = $row['paystatus'];
$mobile = $row['mobile'];
$email = $row['email'];
$datee = $row['datee'];
$subtotal = $row['subtotal'];
$grandtotal = $row['grandtotal'];
$modeofpayment = $row['modeofpayment'];
$discription = $row['discription'];
$sac = $row['sac'];
$table_data .= '<tr id="tr_'.$invoice_no.'" ><td>'.$invoice_no.'</td><td>'.$customer_id.'</td><td>'.$start_date.'</td><td>'.$end_date.'</td><td>'.$grandtotal.'</td><td>'.$paystatus.'</td><td>'.$modeofpayment.'</td><td><a target="_blank" href="viewcustomerdetailinvoice.php?invoice_no='.$invoice_no.'"><button type="button" class="btn btn-primary" ><i class="fa fa-user"></i></button></a></td></tr>';
}
}
?>

Update php SQL when checkbox check (no submit button)

I am pulling data out of a database and displaying in a table. I would like my checkbox, when checked/unchecked, to auto-update the value in the database without using a submit button to trigger the action. I'm new to AJAX and tried to adapt some code. I cannot get it to work. One major thing I don't understand is what '#state_span' is for?
Data Page (HTML)
$sql = "SELECT * FROM Orders ORDER BY " .$order;
$myData = mysqli_query($dbconnect, $sql);
while ($record = mysqli_fetch_array($myData)){
if ($record['Sent'] == 0) {
$sent = "";
} else {
$sent = "checked";
}
if ($record['Paid'] == 0) {
$paid = "";
} else {
$paid = "checked";
}
echo "<tr>";
echo '<td class="MenuLeft">' . $count . "</td>";
echo '<td class="MenuMid">' . $record['Name'] . "</td>";
echo '<td class="MenuRight"><input type="checkbox"
name="Sent"
id="'. $record['ID'] .'"
class="ChkSwitch"' . $sent . ' ></td>';
echo '<td class="MenuRight"><input type="checkbox"
name="Paid"
id="'. $record['ID'] .'"
class="ChkSwitch"' . $paid . ' ></td>';
echo "</tr>";
echo '<script>
$(document).ready(function() {
$(".ChkSwitch").click(function() {
var id = this.id;
var col = this.name; //Tell us what column to update
var state = this.checked ? 1 : 0;
$("#state_span").load("ChkUpdate.php?d="+id+"&col="+col+"&state="+state);
}
}
</script>
';
PHP
$id = $_GET['id'];
$state= $_GET['state'];
$col= $_GET['col'];
include("dbconnect.php");
$query = "UPDATE Orders SET '$col' = '$state' WHERE ID = '$id' ";
mysqli_query($dbconnect, $query);

how to export html table to excel, with pagination

I have a form which displays mysql data in the form of an HTML table, using pagination of 5 records per page. I'm trying to export my table to excel, but it's only exporting data of the rows that are currently show, meaning if there are 20 rows, it only shows the first 5 as those get displayed. How can I make it export the one's that are not being displayed but still part of the search? I saw a few other people with a similar question but none have answers( How to export all HTML table rows to Excel file from a paginated table?). Hopefully I can get one!
<?php
if(isset($_GET['submit']) || isset($_GET['page'])){
// Setting up the Pagination below
echo '<center>';
$page_query = "SELECT * FROM tbl_call_log_detail ";
$page_query .= "WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='') ";
$page_result = mysqli_query($conn, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
$start_loop = $page;
$difference = $total_pages - $page;
if($difference <= $total_pages){
$start_loop = $total_pages - $difference;
}
$end_loop = $start_loop + 2;
if($end_loop > $total_pages){
$end_loop = $total_pages;
}
if($difference > $total_pages){
$end_loop = $total_pages;
}
echo '<div class = "center">';
echo '<div class = "pagination">';
if($page > 1){
echo "<a href= 'dealer_call_log.php?page=1".$urlparameter."'>First</a>";
echo "<a href= 'dealer_call_log.php?page=".($page - 1).$urlparameter."'> << </a>";
}
for ($i = $start_loop; $i <= $end_loop; $i++){
echo "<a href= 'dealer_call_log.php?page=".$i.$urlparameter."'>".$i."</a>";
}
if($page < $end_loop){
echo "<a href= 'dealer_call_log.php?page=".($page + 1).$urlparameter."'> >> </a>";
echo "<a href= 'dealer_call_log.php?page=".$total_pages.$urlparameter."'>Last</a>";
}
if($page < 1){
$page = 1;
}
echo '</div>';
echo '</div>';
echo '<br>';
$sql = "SELECT Name, SFID, Comment, Time FROM tbl_call_log_detail
WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='')
ORDER BY Time DESC LIMIT $start_from, $record_per_page ";
$result = mysqli_query($conn, $sql);
$row = mysqli_num_rows($result);
$all_property = array();
echo "<table class = 'data-table' border = '1' cellpadding = '9' bgcolor = '#CCCCCC' id = 'data-table'>
<tr class = 'data-heading'>";
while($property = mysqli_fetch_field($result)){
echo '<td><b> '. $property ->name. ' </b></td>';
array_push($all_property, $property ->name);
}
echo '</tr>';
while ($row = mysqli_fetch_array($result)){
echo '<tr>';
foreach($all_property as $item){
echo '<td> '. $row[$item] . ' </td>';
}
echo '</tr>';
echo '</center>';
}
echo '</table>';
echo '<br>';
?>
// This is what is getting the current rows, but not all
<input type = "submit" onclick = "window.open('data:application/vnd.ms-excel, '+encodeURIComponent(document.getElementById('data-table').outerHTML));" value = "Export into excel" />
<?php
}
?>
UPDATE: Found the answer I was looking for I simply ran a new sql query without the LIMIT clause and stored it in a hidden table. I then use the hidden table to export data
// SQL and hidden table for exporting to excel
$page_query2 = "SELECT * FROM tbl_call_log_detail ";
$page_query2 .= "WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='') ORDER BY TIME DESC ";
$page_result2 = mysqli_query($conn, $page_query2);
$row2 = mysqli_num_rows($page_result2);
$all_property2 = array();
echo "<table class = 'data-table2' border = '1' cellpadding = '9' bgcolor = '#CCCCCC' id = 'data-table2' hidden>
<tr class = 'data-heading2'>";
while($property = mysqli_fetch_field($page_result2)){
echo '<td><b> '. $property ->name. ' </b></td>';
array_push($all_property2, $property ->name);
}
echo '</tr>';
while ($row2 = mysqli_fetch_array($page_result2)){
echo '<tr>';
foreach($all_property2 as $item){
echo '<td> '. $row2[$item] . ' </td>';
}
echo '</tr>';
echo '</center>';
}
echo '</table>';
?>
<input type = "submit" onclick = "window.open('data:application/vnd.ms-excel, '+encodeURIComponent(document.getElementById('data-table2').outerHTML));" value = "Export into excel" />
<?php
}
?>
You can use JQuery table2excel plugin following is the link
http://www.jqueryscript.net/table/Export-Html-Table-To-Excel-Spreadsheet-using-jQuery-table2excel.html
Try following code pen to only JavaScript
https://codepen.io/kostas-krevatas/pen/mJyBwp

Replace div contents with jQuery on form submit within PHP loop

I have this jQuery form being outputted in a PHP while loop if the button has not previously been clicked and just an image with the value if it has, the function is like facebooks like button where when the user clicks the button the icon changes so its not clickable any longer and the value increments by 1. The form submission works but I cannot seem to update the icon image and value count in the feed without effecting all the other buttons and values in the feed… I tried jQuery replaceWith() but it replaces all the #bumpCont divs in the feed…
index.php
<div class="images">
<?php
while($row = $result2->fetch_assoc()){
$path = $row['path'];
$user = $row['user'];
$id = $row['id'];
$desc = $row['desc'];
$update = $row['update_date'];
$bump = $row['bump'];
$timeFirst = strtotime($date);
$timeSecond = strtotime($update);
$timeSecond = $timeSecond + 86400;
$timer = $timeSecond - $timeFirst;
?>
<?php if(empty($desc)){}else{?><div id="desc"><?php echo $desc;?></div><?php }?>
<img id="pic" src="uploads/<?php echo $path;?>"/>
<div id="userCont">
<div id="user"><a rel="external" href="user_profile.php?user='.$user.'"><?php echo $user;?></a></div>
<div id="timer"><?php echo $timer;?></div>
<?php
if(in_array($path, $mypath)) {
echo '<div id="bumpCont"><img id="bump" style="height:55px;right:8px;top: 2px;position: relative;" src="../img/bumpg.png"/><span id="bumpCount">'.$bump.'</span></div>';
}else{
echo '<form method="post" id="bumpF" data-ajax="false">';
echo '<input name="id" data-ajax="false" id="field_'.$id.'" type="hidden" value="'.$id.'" />';
echo '<div id="bumpCont"><input type="image" style="height:55px;right:8px;top: 2px;position: relative; " id="bump" src="../img/bump.png" id="searchForm" onclick="SubmitForm('.$id.');" value="Send" /><span id="bumpCount">'.$bump.'</span></div>';
echo ' </form>';
}
?>
</div>
<?php
}
?>
//Submit Form
function SubmitForm(id) {
event.preventDefault();
var name = $('#field_'+id).val();
console.log(name);
$.post("bump.php", {name: name},
function(data) {
$( "#bumpCont" ).replaceWith( '<div id="bumpCont"><img id="bump" style="height:55px;right:8px;top: 2px;position: relative;" src="../img/bumpg.png"/><span id="bumpCount">' + data + '</span></div>' );
}
Bump.php -
$id = $_POST['name'];
$sessionUser = $_SESSION['userSession'];
// GET USERNAME
$sql = "SELECT * FROM userbase WHERE user_id='$sessionUser'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$myname = $row['username'];
}
}
$bump = 1;
$sql = "SELECT * FROM images WHERE id=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$bump = $row['bump'];
$path = $row['path'];
$desc = $row['desc'];
$post_user = $row['user'];
$bump++;
}
}
$bumpC = 0;
$sql = "SELECT * FROM bumped WHERE path='$path' AND myname ='$myname'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$bumpC++;
}
}
echo $bump;
if($bumpC >= 1){
}else{
$sql = "INSERT INTO `bumped` ( `myname`,`path`, `description`, `post_user`) VALUES ( '$myname','$path', '$desc', '$post_user')";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "UPDATE images SET update_date='$date' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error updating record: " . $conn->error;
}
$sql = "UPDATE images SET bump=$bump WHERE id=$id";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error updating record: " . $conn->error;
}
}
First look shows me a problem of Elements with same ID in loop.
You could have same class to multiple elements.
<div class="bumpCont"><span class="bumpCount">1</span></div>
<div class="bumpCont"><span class="bumpCount">2</span></div>
Use $(this)
Based on the click on particular element, you can change contents.
$('.bumpCount').click(function(){
$(this).html(parseInt($(this).html) + 1);
});
Hope this helps you.
$('.bumpCount').click(function(){
$(this).html(parseInt($(this).html()) + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bumpCont"><span class="bumpCount">1</span></div>
<div class="bumpCont"><span class="bumpCount">2</span></div>

Grab two values in loop, check box and variable. Only grabbing checkbox? php w screenshot

i make a sql query asking for data(its a text question), i output the (question) with a checkbox to the left of it and an input field underneath it to give point worth to it(like a teacher making an exam) . All in a loop w arrays. It outputs the correctly checked questions but only will assign point values to first three questions if there checked. so if i check q1 q2 and q4 it will output q1 q2 q4 and q1 points q2points. Thats my problem, I only want to be able to select three total questions and assign those questions their points.
php in the html
$sql = " SELECT Question FROM examQuestions";
$result = mysqli_query($dbCon, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<input type="checkbox" name="checkboxvar[]" value="'.$row["Question"].'">'.$row["Question"].'<input placeholder="10" class="form-control" type="number" name="points[]">'."<br />";
}
}
im trying to output the data using this:
$checkboxvar = $_POST['checkboxvar'];
$examName = $_POST['examName'];
$questionWorth = $_POST['points'];
$i=1;
$total = 0;
while ($i < 4) {
$x = $i - 1;
echo $checkboxvar[$x];
echo $questionWorth[$x]."<br />";
$total = $total + $questionWorth[$x];
$i = $i +1;
}
echo $total;
As I told you in the comments try modifying your code like this:
$sql = " SELECT Question FROM examQuestions";
$result = mysqli_query($dbCon, $sql);
$i = 0;
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<input type="checkbox" name="checkboxvar[]" value="'.$i++.'-'.$row["Question"].'">'.$row["Question"].'<input placeholder="10" class="form-control" type="number" name="points[]">'."<br />";
}
}
And then, to have the right points for the correspondig question something like this:
$checkboxvar = $_POST['checkboxvar'];
$examName = $_POST['examName'];
$questionWorth = $_POST['points'];
$i = 0;
$total = 0;
while ($i < 3) {
$question = explode("-", $checkboxvar[$i]);
echo $question[1];
echo $questionWorth[$question[0]]."<br />";
$total += $questionWorth[$question[0]];
$i++;
}
echo $total;
This should do the work.
If i understand your implied question correctly, you will need some client side (javascript) code that keeps track of the number of checked checkboxes. As soon as one checks three boxes all remaining ones and corresponding text boxes are disabled.
for naive vanilla js solution your php could look like this:
$index = 0;
while($row = mysqli_fetch_assoc($result)) {
echo "<label><input class='questions' type='checkbox' name='question_{$index}' value='{$row["Question"]}' on_change='limit_to_three(this);'>{$row["Question"]}<label><br>";
echo "<input class='scores' name='score_{$index}'><br>";
$index++;
}
For modern browsers you would need the following in your javascript :
var selected_count = 0;
function limit_to_three(selected_checkbox) {
if (selected_checkbox.checked) {
selected_count++;
} else {
selected_count--;
}
var limit_reached = (selected_count == 3);
var checkboxes = document.getElementsByClassName('questions');
var scores = document.getElementsByClassName('scores');
for (var i=0; i<checkboxes.length; i++) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = scores[i].disabled = limit_reached;
}
}
}
Now, upon submit, you can assume that only checked question checkboxes will be submitted, so your php code could be like this:
$total = 0;
$length = strlen('questions_');
foreach ($_POST as $name => $value) {
if (substr($name, 0, $length) == 'questions_') {
$index = substr($name, $length - strlen($name));
echo $_POST[$name];
echo "<br>";
echo $_POST["scores_{$index}"];
$total += $_POST["scores_{$index}"];
}
}
As i said, this is a naive implementation, that sends question texts back and forth. If i were you i would add ID column to your questions table and use it instead of dynamically generated indexes
Then your html could be generated like this:
while($row = mysqli_fetch_assoc($result)) {
echo "<label><input class='questions' type='checkbox' name='question_{$index}' value='{$row["ID"]}' on_change='limit_to_three(this);'>{$row["Question"]}<label><br>";
echo "<input class='scores' name='score_{$row["ID"]}'><br>";
}
and your receiving php could be like this:
$checked = explode(',', $_POST['questions']);
for ($checked as $id) {
$total += $_POST["scores_{$id}"];
}
Also you could retrieve the checked questions by
$sql = "SELECT * FROM Questions WHERE ID IN ({$_POST['questions']})";

Categories

Resources