So I've been looking at this page for hours and hours and I can't seem to figure out what the problem is here. I had this issues with all links previously, where I would lick a link to filter/sort database results, click a page link to go to the next page and it would display the second page without any filtered results. I resolved this for "Most Wins", "Best Save %" and "Best Goals Against" by the use of sessions, but for some reason it is still doing this when I try and filter results via my range sliders form. It works when I adjust the sliders, and submit, but if I click another page, once again, it show all results in the database. Can anyone see as to why it might be doing this? I've tried both post and get methods from the form but it didn't seem to work, but if anyone could provide some advice I would greatly appreciate it!!
Here is the code:
<body>
<header>
<div class="header-container">
<nav>
<img src="images/header_img.png" alt="Golaie Gear Online"/>
<ul>
<li>Browse Goalies</li>
<li>Browse Gear</li>
<li>Admin</li>
</ul>
<form method="get" action="<?php echo "generalsearch.php?q=$searchvalue"; ?>" class="search-field">
<input name="search" type="text" placeholder="Search">
<button type="submit" title="Search" id="submit"><img src="images/header_srch.png" alt="search"/></button>
</form>
</nav>
</div>
<div style="clear:both;"></div>
</header>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<style type="text/css">
#win-range, #gaa-range, #sv-range{
width: 160px;
font-size: 10px;
margin: 0 auto;
}
#win-range a, #gaa-range a, #sv-range a{
margin-top: 0px !important;
padding: 0 !important;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function(){
$("#win-range").slider({
range: true,
min: 1,
max: 1000,
values: [1, 1000],
slide: function(event, ui) {
// in order to pass the user selected values to your app, we will use jQuery to prepopulate certain hidden form elements, then grab those values from the $_POST
$("#minwins").val(ui.values[0]);
$("#maxwins").val(ui.values[1]);
$("#winamount").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#winamount").val($("#win-range").slider("values", 0) + " - " + $("#win-range").slider("values", 1));
});
$(function(){
$("#gaa-range").slider({
range: true,
min: 0,
max: 10,
values: [0, 10],
slide: function(event, ui) {
// in order to pass the user selected values to your app, we will use jQuery to prepopulate certain hidden form elements, then grab those values from the $_POST
$("#mingaa").val(ui.values[0]);
$("#maxgaa").val(ui.values[1]);
$("#gaaamount").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#gaaamount").val($("#gaa-range").slider("values", 0) + " - " + $("#gaa-range").slider("values", 1));
});
$(function(){
$("#sv-range").slider({
range: true,
min: 750,
max: 1000,
values: [750, 1000],
slide: function(event, ui) {
// in order to pass the user selected values to your app, we will use jQuery to prepopulate certain hidden form elements, then grab those values from the $_POST
$("#minsv").val(ui.values[0]);
$("#maxsv").val(ui.values[1]);
$("#svamount").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#svamount").val($("#sv-range").slider("values", 0) + " - " + $("#sv-range").slider("values", 1));
});
</script>
<?php
include("includes/header.php");
include("includes/mysqli_connect.php");
$sortDesc = $_REQUEST['sortstats'];
$sortAsc = $_REQUEST['sortstatslow'];
$minwins = $_GET['minwins'];
$maxwins = $_GET['maxwins'];
$mingaa = $_GET['mingaa'];
$maxgaa = $_GET['maxgaa'];
$minsv = $_GET['minsv'];
$maxsv = $_GET['maxsv'];
// FILTERING YOUR DB
$sortstats = $_GET['sortstats'];
$sortstatslow = $_GET['sortstatslow'];
$getminwins = $_REQUEST['getminwins'];
$getmaxwins = $_REQUEST['getmaxwins'];
$getmingaa = $_REQUEST['getmingaa'];
$getmaxgaa = $_REQUEST['getmaxgaa'];
$getminsv = $_REQUEST['getminsv'];
$getmaxsv = $_REQUEST['getmaxsv'];
// paging
$getcount = mysqli_query ($con,"SELECT COUNT(*) FROM Player");
$postnum = mysqli_result($getcount,0);// this needs a fix for MySQLi upgrade; see custom function below
$limit = 6; //how many blog posts per page you will see.
if($postnum > $limit){
$tagend = round($postnum % $limit,0);
$splits = round(($postnum - $tagend)/$limit,0);
if($tagend == 0){
$num_pages = $splits;
}else{
$num_pages = $splits + 1;
}
if(isset($_GET['pg'])){
$pg = $_GET['pg'];
}else{
$pg = 1;
}
$startpos = ($pg*$limit)-$limit;
$limstring = "LIMIT $startpos,$limit";
}else{
$limstring = "LIMIT 0,$limit";
}
// MySQLi upgrade: we need this for mysql_result() equivalent
function mysqli_result($res, $row, $field=0) {
$res->data_seek($row);
$datarow = $res->fetch_array();
return $datarow[$field];
}
?>
<div class="listingcontainer">
<div class="sidebar">
<h3>Sort By:</h3>
Most Wins
Best Goals Against
Best Save %
<hr/>
<h3>Custom Filter</h3>
<br/>
<div class="custom-filter">
<form name="filters" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get" id="filters">
<label for="winamount">Win Range:</label>
<input type="text" id="winamount" />
<div style="clear:both;"></div>
<input type="hidden" id="minwins" name="minwins" value="0" />
<input type="hidden" id="maxwins" name="maxwins" value="1000" />
<div id="win-range"></div>
<br/>
<label for="gaaamount">GAA:</label>
<input type="text" id="gaaamount" /><br />
<div style="clear:both;"></div>
<input type="hidden" id="mingaa" name="mingaa" value="0" />
<input type="hidden" id="maxgaa" name="maxgaa" value="10" />
<div id="gaa-range"></div>
<br/>
<label for="svamount">SV %:</label>
<input type="text" id="svamount" /><br />
<div style="clear:both;"></div>
<input type="hidden" id="minsv" name="minsv" value="750" />
<input type="hidden" id="maxsv" name="maxsv" value="1000" />
<div id="sv-range"></div>
<input type="submit" name="submit" id="submit"/>
</form>
</div>
</div>
<div class="main-listings">
<h1>Current NHL Goaltenders</h1>
<?php
session_start();
if($_SESSION['allresults'])
{
$result = mysqli_query($con, "SELECT * FROM Player ORDER BY PlayerID ASC $limstring");
if(isset($sortstats)){//THIS WORKS
session_start();
$_SESSION['sortStatsDesc'] = session_id();
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstats DESC $limstring ");
$filter = "sortstats={$sortDesc}";
}
if(isset($sortstatslow)) {//THIS WORKS
session_start();
$_SESSION['sortStatsAsc'] = session_id();
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstatslow ASC $limstring ");
$filter = "sortstatslow={$sortAsc}";
}
if(isset($minwins) || isset($maxwins) || isset($mingaa) || isset($maxgaa) || isset($minsv) || isset($maxsv))//THIS SEEMS TO WORK
{
session_start();
$_SESSION['customFilter'] = session_id();
$result = mysqli_query($con, "SELECT * FROM Player WHERE Wins BETWEEN '$minwins' AND '$maxwins' AND
GAA BETWEEN '$mingaa' AND '$maxgaa' AND SavePerc BETWEEN '$minsv' AND '$maxsv'
ORDER BY PlayerID ASC $limstring") or die (mysql_error());
$filter = "getminwins={$minwins}&getmaxwins={$maxwins}&getmingaa={$mingaa}&getminsv={$minsv}&getmaxsv={$maxsv}";
}
}
else if($_SESSION['sortStatsDesc'])//THIS WORKS
{
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstats DESC $limstring ");
}
else if($_SESSION['sortStatsAsc'])//THIS WORKS
{
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstatslow ASC $limstring ");
}
else if($_SESSION['customFilter'])//DON'T KNOW IF THIS IS DOING ANYTHING
{
$result = mysqli_query($con, "SELECT * FROM Player WHERE Wins BETWEEN '$getminwins' AND '$getmaxwins' AND
GAA BETWEEN '$getmingaa' AND '$getmaxgaa' AND SavePerc BETWEEN '$getminsv' AND '$getmaxsv'
ORDER BY PlayerID ASC $limstring");
}
else{
}
while($row = mysqli_fetch_array($result)){
$name = $row['LastName'] . ", " . $row['FirstName'];
$wins = $row['Wins'];
$pid = $row['PlayerID'];
$image = $row['Picture'];
$gaa = $row['GAA'];
$sv = $row['SavePerc'];
echo "<div class=\"player-listing\">";
echo "<div class=\"image-holder\">";
echo "<span class=\"helper\"></span>";
echo "<img src=\"admin/thumbs/$image\" alt=\"$name\">";
echo "</div>";
echo "<div style=\"clear:both;\"></div>";
echo "$name";
echo "<table align=\"center\">";
echo "<tr>";
echo "<td style=\"border-bottom: 1px solid #212121;\">Wins</td>";
echo "<td style=\"border-bottom: 1px solid #212121;\">GAA</td>";
echo "<td style=\"border-bottom: 1px solid #212121;\">SV%</td>";
echo "</tr>";
echo "<tr>";
echo "<td>$wins</td>";
echo "<td>$gaa</td>";
echo "<td>.$sv</td>";
echo "</tr>";
echo "</table>";
echo "</div>";
}
// paging links:
echo "<div class=\"paging\">";
if($postnum > $limit){
echo "<span class=\"page-numbers\"><strong>Pages:</strong> </span>";
$n = $pg + 1;
$p = $pg - 1;
$thisroot = $_SERVER['PHP_SELF'];
if($pg > 1){
echo "<< prev ";
}
for($i=1; $i<=$num_pages; $i++){
if($i!= $pg){
echo "$i ";
}else{
echo "$i ";
}
}
if($pg < $num_pages){
// INSERT QUERY STRING VARIBLE TO CARRY OVER DB QUERY
echo "next >>";
}
echo " ";
}
// end paging
echo "</div>";
?>
<br/>
</div>
<div style="clear:both;"></div>
</div>
EDIT: I fixed the paging issue by adding this into my code:
$getcount = mysqli_query ($con,"SELECT COUNT(*) FROM Player");
if($_SESSION['customFilter']){
$getcount = mysqli_query ($con,"SELECT COUNT(*) FROM Player WHERE Wins BETWEEN '$minwins' AND '$maxwins' AND
GAA BETWEEN '$mingaa' AND '$maxgaa' AND SavePerc BETWEEN '$minsv' AND '$maxsv'");
}
But it's still giving me grief when I click next page. I don't think the filter values are carryying over for some reason.
Remove all the existing session_start() and add one on the first rule of the page, like:
<?php
session_start();
?>
//Your html/js/php
...
...
For session to works the very first instruction you have to call is "session_start()". You should call it only once and at the very beginning of your script.
<?php session_start() ?>
// rest of code PHP/HTML/JS/CSS/anything
Related
I am building a database of different devices which is displayed in a page which sells medical devices. When a user adds a quantity of the device to the cart, I want the database to be updated with (stock - quantity in cart) I am trying to do this on PHP but am having no luck. My attempt and code is below.
Here is a snippet of my attempt. I'm not sure where to place this in the code below.
<?php
$value = isset($_POST['item']) ? $_POST['item'] : 1; //to be displayed
if(isset($_POST['incqty'])){
$value += 1;
$query = "UPDATE products SET stock= (stock-$product_qty) WHERE product_name=$product_name";
mysql_select_db('products');
$retval = mysql_query($query,$mysqli);
}
?>
This is code for index.php
<?php
session_start();
include_once("config.php");
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 align="center">Products </h1>
<!-- View Cart Box Start -->
<?php
if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0)
{
echo '<div class="cart-view-table-front" id="view-cart">';
echo '<h3>Your Shopping Cart</h3>';
echo '<form method="post" action="cart_update.php">';
echo '<table width="100%" cellpadding="6" cellspacing="0">';
echo '<tbody>';
$total =0;
$b = 0;
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$product_color = $cart_itm["product_color"];
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td>Qty <input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /> Remove</td>';
echo '</tr>';
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
echo '<td colspan="4">';
echo '<button type="submit">Update</button>Checkout';
echo '</td>';
echo '</tbody>';
echo '</table>';
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
}
?>
<!-- View Cart Box End -->
<!-- Products List Start -->
<?php
$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price, stock FROM products ORDER BY id ASC");
if($results){
$products_item = '<ul class="products">';
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
$products_item .= <<<EOT
<li class="product">
<form method="post" action="cart_update.php">
<div class="product-content"><h3>{$obj->product_name}</h3>
<div class="product-thumb"><img src="images/{$obj->product_img_name}"></div>
<div class="product-desc">{$obj->product_desc}</div>
<div class="product-info">
Price {$currency}{$obj->price}
<fieldset>
<label>
<span>Color</span>
<select name="product_color">
<option value="Black">Black</option>
<option value="Silver">Silver</option>
</select>
</label>
<label>
<span>Quantity</span>
<input type="text" size="2" maxlength="2" name="product_qty" value="1" />
</label>
</fieldset>
<input type="hidden" name="product_code" value="{$obj->product_code}" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="{$current_url}" />
<div align="center"><button type="submit" id="updateb" class="add_to_cart">Add</button></div>
</div></div>
</form>
</li>
EOT;
}
$products_item .= '</ul>';
echo $products_item;
}
?>
<!-- Products List End -->
</body>
</html>
This is code for cart_update.php
<?php
session_start();
include_once("config.php");
//add product to session or create new one
if(isset($_POST["type"]) && $_POST["type"]=='add' && $_POST["product_qty"]>0)
{
foreach($_POST as $key => $value){ //add all post vars to new_product array
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
}
//remove unecessary vars
unset($new_product['type']);
unset($new_product['return_url']);
//we need to get product name and price from database.
$statement = $mysqli->prepare("SELECT product_name, price, stock FROM products WHERE product_code=? LIMIT 1");
$statement->bind_param('s', $new_product['product_code']);
$statement->execute();
$statement->bind_result($product_name, $price, $stock);
while($statement->fetch()){
//fetch product name, price from db and add to new_product array
$new_product["product_name"] = $product_name;
$new_product["product_price"] = $price;
$new_product["product_stock"] = $stock;
if(isset($_SESSION["cart_products"])){ //if session var already exist
if(isset($_SESSION["cart_products"][$new_product['product_code']])) //check item exist in products array
{
unset($_SESSION["cart_products"][$new_product['product_code']]); //unset old array item
}
}
$_SESSION["cart_products"][$new_product['product_code']] = $new_product; //update or create product session with new item
}
}
//update or remove items
if(isset($_POST["product_qty"]) || isset($_POST["remove_code"]))
{
//update item quantity in product session
if(isset($_POST["product_qty"]) && is_array($_POST["product_qty"])){
foreach($_POST["product_qty"] as $key => $value){
if(is_numeric($value)){
$_SESSION["cart_products"][$key]["product_qty"] = $value; //change
}
}
}
//remove an item from product session
if(isset($_POST["remove_code"]) && is_array($_POST["remove_code"])){
foreach($_POST["remove_code"] as $key){
unset($_SESSION["cart_products"][$key]);
}
}
}
//back to return url
$return_url = (isset($_POST["return_url"]))?urldecode($_POST["return_url"]):''; //return url
header('Location:'.$return_url);
?>
This is code for view_cart.php
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View shopping cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css"></head>
<body>
<h1 align="center">View Cart</h1>
<div class="cart-view-table-back">
<form method="post" action="cart_update.php">
<table width="100%" cellpadding="6" cellspacing="0"><thead><tr><th>Quantity</th><th>Name</th><th>Price</th><th>Total</th><th>Remove</th></tr></thead>
<tbody>
<?php
if(isset($_SESSION["cart_products"])) //check session var
{
$total = 0; //set initial total value
$b = 0; //var for zebra stripe table
foreach ($_SESSION["cart_products"] as $cart_itm)
{
//set variables to use in content below
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$product_color = $cart_itm["product_color"];
$subtotal = ($product_price * $product_qty); //calculate Price x Qty
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //class for zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td><input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td>'.$currency.$product_price.'</td>';
echo '<td>'.$currency.$subtotal.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></td>';
echo '</tr>';
$total = ($total + $subtotal); //add subtotal to total var
}
$grand_total = $total + $shipping_cost; //grand total including shipping cost
foreach($taxes as $key => $value){ //list and calculate all taxes in array
$tax_amount = round($total * ($value / 100));
$tax_item[$key] = $tax_amount;
$grand_total = $grand_total + $tax_amount; //add tax val to grand total
}
$list_tax = '';
foreach($tax_item as $key => $value){ //List all taxes
$list_tax .= $key. ' : '. $currency. sprintf("%01.2f", $value).'<br />';
}
$shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
}
?>
<tr><td colspan="5"><span style="float:right;text-align: right;"><?php echo $shipping_cost. $list_tax; ?>Amount Payable : <?php echo sprintf("%01.2f", $grand_total);?></span></td></tr>
<tr><td colspan="5">Add More Items<button type="submit">Update</button></td></tr>
</tbody>
</table>
<input type="hidden" name="return_url" value="<?php
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo $current_url; ?>" />
</form>
</div>
</body>
</html>
your variables $product_qty and $product_name are not defined and in the query pass the product name in the quotes as your query is in double quotes so pass name in the single quotes.
Also it will be better if you update using primary id not by name.
I'm trying to populate multiple form fields from a generated button in a foreach statement. I don't have a vast knowledge of JS so I don't know if I'm just not thinking of a certain function or not.
I have the following code and I'm able to get title to populate in the form but I have no clue where to start for populating content as well based of the same button. ex: one button will load a specific title and content value while another edit button will load another specific title and content value.
//Announcement table select
$sql = "SELECT * FROM `announcements` ORDER BY `startDate` DESC"; //I want to see all existing announcements from database
$announcement = $dbConnect->query($sql);//execute query
$a = 0;
?>
<script type="text/javascript">
function changeText(title, content){
document.getElementById('title').value = title.id;
document.getElementById('content').value = document.getElementById(content).getAttribute('data-content');
}
</script>
<?php
foreach ($announcement as $row){ //Displays title, startDate, endDate from announcement table from database
$x[$a] = $row["title"];
$y[$a] = $row["content"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
echo '<input id="'.$x[$a].'" type=button class=test onclick="changeText(this, '.$y[$a].');" value="Edit">';
echo '<p id="'.$y[$a].'" data-content="'.$row["content"].'">test</p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
?>
</div>
</div>
</div> <!--m4 ends here-->
<div class="col m8 s8"> <!--m8 starts here-->
<div class="titleboxmargin grey" style="width:100%;">
<div class="bar yellow"></div>
<img class="boxicon" src="../images/announcementsicon.svg">
<h3 class="title">Announcements</h3>
</div>
<div class="col yellow-light"> <!--Announcement Form Starts-->
<form action="includes/postAnnouncement.php" method="post">
<ul class="yellow-form">
<li class="textfield-container">
<label for="text" class="textlabelblack">Title:</label>
<input id="title" name= "title" type="text" placeholder="Title of My Announcement">
</li>
<li class="textfield-container">
<label for="textarea" class="textlabelblack">Start Date:</label>
<input type="date" id="startDate" name="startDate">
</li>
<li class="textfield-container">
<label for="textarea" class="textlabelblack">End Date:</label>
<input type="date" id="endDate" name="endDate">
</li>
<li class="textfield-container">
<label for="textarea" class="textlabelblack">Announcement:</label>
<textarea id="content" name="content" rows="7"></textarea>
</li>
<li class="textfield-container">
<div class="leftsidebutton">
<input type="submit" class="button" style="width:auto; padding:5px; border:0;" name="register" value="Submit the form"/><!--Action: Attempts to Redirect to postAnnouncement.php-->
</div>
</li>
</ul>
</form>
The following code works
Edit:
<script type="text/javascript">
function changeText(title, content){
document.getElementById('content').value = document.getElementById(content).getAttribute('data-content');
document.getElementById('title').value = document.getElementById(title).getAttribute('data-content');
}
</script>
<?php
foreach ($announcement as $row){ //Displays title, startDate, endDate from announcement table from database
$tile = $row["announcementID"] * 2;
$cont = $row["announcementID"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
echo '<input id="'.$tile.'" data-content="'.$row["title"].'" type=button class=test onclick="changeText(id, '.$cont.');" value="Edit">';
echo '<p id="'.$cont.'" data-content="'.$row["content"].'">test</p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
?>
You could add a second parameter to your onclick handler:
$a = 0;
?>
<script type="text/javascript">
function changeText(elem, content){
document.getElementById('title').value = elem.id;
/*
* Here we get the value of the hidden content by the passed
* in id and assign it to the value of the #content form element
*/
document.getElementById('content').value = document.getElementById(content).value;
}
</script>
<?php
foreach ($announcement as $row){ //Displays title, startDate, endDate from announcement table from database
$x[$a] = $row["title"];
$y[$a] = $row["content"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
echo '<input id="'.$x[$a].'" type=button class=test onclick="changeText(this, '.$y[$a].'); startDate('.$y[$a].'); " value="Edit">';
echo '<p style="display:hidden;" id="'.$y[$a].'" ></p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
EDIT:
$a = 0;
?>
<script type="text/javascript">
function changeText(elem, contentID){
var contentElem = document.getElementById(contentID);
document.getElementById('title').value = elem.getAttribute('data-title');
/*
* Get the value of the hidden content's data attribute by the passed
* in id and assign it to the value of the #content form element
*/
document.getElementById('content').value = contentElem.getAttribute('data-content');
}
</script>
<?php
// Let's get $index as well
foreach ($announcement as $index => $row){ //Displays title, startDate, endDate from announcement table from database
$x[$a] = $row["title"];
$y[$a] = $row["content"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
// Not sure if I'm escaping quotes correctly on this line:
echo '<input id="title'.$index.'" data-title="'.$x[$a].'" type=button class=test onclick="changeText(this, \"content'.$index.'\"); startDate('.$y[$a].'); " value="Edit">';
// Generate a unique id that we can reference
// and add `data-content` attribute
echo '<p style="display:hidden;" id="content'.$index.'" data-content="'.$y[$a].'"></p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
I am not sure what your title and content values are, but I suspect they are not valid HTML element IDs. I think it would be better to avoid using the DOM as a data store and instead create a JSON representation of your announcement table in your script. My PHP is a little rusty, but it should be something similar to:
<script>
var rows = <?php echo json_encode($announcement); ?>;
</script>
Hopefully this will produce something like the following:
var rows = [
{
"title": "Title One",
"content": "Content One"
},
{
"title": "Title Two",
"content": "Content Two"
}
];
This way, our changeText function need only accept a row index as parameter:
function changeText (index) {
document.getElementById('title').value = rows[index].title;
document.getElementById('content').value = rows[index].content;
}
All that is left is to pass the row index where we call changeText:
<?php foreach ($announcement as $index => $row) { ?>
<!-- echo your HTML markup here. -->
<button onclick="changeText(<?php echo $index; ?>);">Edit</button>
<?php } ?>
when click the checkbox another modal will pop up for the quantity of the selected value and I check Geda Jumuad and add "2" as quantity value but then the value '2' was put in the beginning of the checboxes . .
I want to put the quantity value beside the selected checkbox.. please help me.
heres my code
<b>Menu: </b>
<br>
<div class="menucontainers" style="background: #fff; border-style: solid; border-width: 2px; border-color:#ccccff; width: 400px; height:150px; overflow:auto;">
<!-- <img src ="../1.jpg" class="img-rounded"> -->
<ul>
<?php
include ('myConnection.php');
$query = "Select * from menu_category order by menu_cat_name";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$menucatname = $row['menu_cat_name'];
$menucatid = $row['menu_cat_id_inc'];
?>
<li class="dropdownz" style="border-style: solid;border-color: white; border-bottom: 2px; border-left: 2px; border-right: 2px">
<i id = "arrow" class="icon-arrow"></i><?php echo "$menucatname"; ?>
<ul id="ddownz-menu" class="dropdownz-menu">
<li>
<?php
$query2 = "Select * from menu where menu_cat_id_inc = '$menucatid' order by menu_name";
$result2 = mysql_query($query2);
$countme = 0;
while ($row2 = mysql_fetch_array($result2)) {
$menuname = $row2['menu_name'];
$price = $row2['price'];
if ($countme % 2 == 0)
{
?>
<div class="col col-md-6">
<input type="checkbox" id="newmenu" name="cbox[]" style="font-size:15px" value="<?php echo $row2['menu_id_inc'];?>">
<?php
echo '<span id = "quantity" style = "color:black;"></span>'. " " . "$menuname";
?>
</div>
<?php
}
else
{
?>
<div class="col col-md-4">
<input type="checkbox" id="newmenu" name="cbox[]" value="<?php echo $row2['menu_id_inc'];?>">
<?php
echo '<span id = "quantity" style = "color:black;"></span>'. " " . "$menuname";
?>
</div>
<?php
}
}
?>
</li>
</ul>
</li>
<?php
}
?>
</ul>
</div>
and for javascript. .
$("#qtyok").click(function () {
var id = $("#menuid").val();
var qty = $("#qtybox").val();
if (qty != '') {
$("#loaderz").show();
$.post("fm_valuemenuload.php", {
id: id,
qty: qty
},
function (data, status) {
$("#loaderz").hide();
$("#modalQty").modal('hide');
$("#message").html('Added');
document.getElementById('quantity').innerHTML = qty;
price += data * qty;
$("#newprice").val(price.toFixed(2));
$("#modalSUCCESS").modal('show');
setTimeout(func1, 3000);
});
}
});
`
I might be misunderstanding your problem but... I think you just got it in the wrong order. Place the span after the $menuname.
Instead of
echo '<span id = "quantity" style = "color:black;"></span>'. " " . "$menuname";
Do
echo "$menuname".' <span id = "quantity" style = "color:black;"></span>';
You also must assign unique ids to your spans. Although your checkboxes are dynamic, you can for example retrieve the value of those checkboxes and append it to 'quantity'. You will have ids 'quantity1', 'quantity2', 'quantity3' produced. Change the previous line of code to
echo "$menuname".' <span id = "quantity'.$row2['menu_id_inc'].'" style = "color:black;"></span>';
You will also have to do something similar in your javascript. Retrieve the checkbox value number in a javascript variable, and append it to 'quantity' here
document.getElementById('quantity' + value).innerHTML = qty;
I am trying to input a value (Rating) from the database when an item is selected. I need to also be able to update that rating and then put that value into another table.
My problem is that I'm trying to figure out how to make the value in the text box be related to the selection made in the drop down. I've found coding to make another option box but cannot figure out how to make that a text box.
REWORDING: Originally when I posted the question I thought it was possible to do this without JQuery and was trying to copy the for loop and run a while loop to populate the text box. I now know that isn't possible and would like to figure out how to run a script to populate a text box on change for the drop down box. The problem being the function has to be connected to the database as well as the drop down.
1. pull the data for the drop down (from the JOURNAL table). 2. Select a journal from that drop down 3. Inside the JOURNAL table a JournalRating has been assigned to every journal pull that value and place inside a textbox.
What I've tried to do is
<?php
include 'dbc.php';
connect();
//insert form values into database
$sql = "SELECT JournalName, JournalID, Rating, JournalActive from JOURNAL where JournalActive = 1;";
//Can take out JournalActive if we do not want it
$result = mysqli_query($conn, $sql);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
$sql2 = "SELECT FName, LName, FacultyID from FACULTY where FacultyActive = 1;";
//Can take out JournalActive if we do not want it
$result2 = mysqli_query($conn, $sql2);
if (!$result2) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
//array to hold all of the data
$journals = array();
//print out all of the first names in the database
$rownumber = 0;
while ($row = mysqli_fetch_assoc($result)) {
$journals[$rownumber][0] = $row['JournalName'];
$journals[$rownumber][1] = $row['JournalID'];
$journals[$rownumber][2] = $row['JournalRating'];
$journals[$rownumber][3] = $row['JournalActive'];
$rownumber++;
}
$faculty = array();
//print out all of the first names in the database
$rownum = 0;
while ($row = mysqli_fetch_assoc($result2)) {
$faculty[$rownum][0] = $row['FName'];
$faculty[$rownum][1] = $row['LName'];
$faculty[$rownum][2] = $row['FacultyID'];
$rownum++;
}
?>
<!DOCTYPE html>
<head>
<link href="styles.css" rel="stylesheet">
<h1> Miami University </h1>
<h4> Information Systems and Analytics Department </h4>
<script>
(function($){
$(function(){
$("#JournalID").on('change', function() {
$("#JournalRating").val($(this).find("option:selected").data('Rating'));
});
});
})(jQuery);
</script>
</head>
<body>
<div class="StyleDiv" >
<!-- coding for journal -->
<form id="form1" name="form1" method="post" action="RR2.php">
<label for="FacultyID">Faculty Name</label>
<select multiple="multiple" name="FacultyID[]" id="FacultyID">
<?php
for($i = 0; $i < sizeof($faculty); $i++) {
print "<option value=\"" . $faculty[$i][2] . "\">" . $faculty[$i][0] .' '. $faculty[$i][1] . "</option>\r\n";
}
?>
</select>
<br class="clear" />
<br class="clear" />
<label for="JournalID">Journal Name</label>
<select name="JournalID" id="JournalID">
<?php
for($i = 0; $i < sizeof($journals); $i++) {
print "<option value=\"" . $journals[$i][1] . "\" data-rating=\"" . $journals[$i][2] . "\">" . $journals[$i][0] . "</option>\r\n";
}
?>
</select>
<br class="clear"/>
<label for="JournalRating">Journal Rating</label><input type="text" name="JournalRating" id="JournalRating" />
<br class="clear" />
<!-- coding for publication -->
<label for="Title">Publication Title</label><input type="text" name="PubID" id="PubID" />
<br class="clear" />
<label for="Year">Year</label><input type="text" name="Year" id="Year" />
<br class="clear" />
<label for="Volume">Volume</label><input type="text" name="Volume" id="Volume" />
<br class="clear" />
<label for="Issue">Issue</label><input type="text" name="Issue" id="Issue" />
<br class="clear" />
<label for="Comments">Comments</label><textarea name="Comments" id="Comments" cols="45" rows="5"></textarea>
<br class="clear" />
<input type="submit" name="Submit" id="Submit" value="Submit" />
<br class="clear" />
</br>
</br>
</div>
</form>
<?php
//Post Parameters
$JournalID = $_POST['JournalID'];
//for($i = 0; $i < sizeof($journals); $i++) {
//if ($JournalID = $journals[$i][1]) {
//$JournalName = $journals[$i][0];
//}
//}
$Year = $_POST['Year'];
$Comments = $_POST['Comments'];
$Volume = $_POST['Volume'];
$Issue = $_POST['Issue'];
$Title = $_POST['Title'];
$JournalRating = $_POST['JournalRating'];
$FacultyMemID = $_POST['FacultyID'];
//Query
//INSERT
$stmt = $conn->prepare(" INSERT INTO PUBLICATION ( JournalID, Year, Comments, Volume, Issue, Title, JournalRating ) VALUES ( ?, ?, ?, ?, ?, ?, ? )");
$stmt->bind_param('sssssss', $JournalID, $Year, $Comments, $Volume, $Issue, $Title, $JournalRating);
$stmt->execute();
$pubID = $stmt->insert_id;
$facmemid = 0;
$stmt = $conn->prepare(" INSERT INTO FACULTYPUBLICATIONS ( FacultyID, PubID ) VALUES ( ?, ? )");
$stmt->bind_param('ii', $facmemid, $pubID);
//for ($_POST['FacultyID'] as $FacultyMemID) {
for($i = 0; $i < sizeof($FacultyMemID); $i++) {
$facmemid = $FacultyMemID[$i];
$stmt->execute();
}
mysqli_close($conn);
?>
</body>
</html>
Add the rating to your HTML using a data attribute:
<select name="JournalID" id="JournalID">
<?php
for($i = 0; $i < sizeof($journals); $i++) {
print "<option value=\"" . $journals[$i][1] . "\" data-rating=\"" . $journals[$i][2] . "\">" . $journals[$i][0] . "</option>\r\n";
}
?>
</select>
Then you can access this using jQuery .data():
(function($) {
$(function() {
$("#JournalID").on('change', function() {
$("#JournalRating").val($(this).find("option:selected").data('rating'));
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="JournalID">
<option>Select a journal</option>
<option value="1" data-rating="3">Journal #1</option>
<option value="2" data-rating="2">Journal #2</option>
<option value="3" data-rating="5">Journal #3</option>
</select>
<br>
Rating: <input id="JournalRating">
I have this script which works once but I can't seem to replicate it inside the same document.
The JQuery:
$("document").ready(function() {
//This first instance works
if($("#add-menu").length) {
$("#add-menu").change(function() {
var datum = 'shortname=' + $(this).val() + '&table=projects';
$.post('proj_query.php', datum, response);
function response(data) {
var jSON = $.parseJSON(data);
$("label:contains('Title:') + input:first").val(jSON.title);
$("label:contains('Medium:') + input:first").val(jSON.medium);
$("label:contains('Dimmensions:') + input:first").val(jSON.description);
$("label:contains('Work Blurb:') + textarea:first").val(jSON.blurb);
}
});
}
//This one doesn't work
if($("#id-blurb").length) {
$("#id-blurb a").click(function() {
if($("#edit-menu").val().length) {
var datum = 'shortname=' + $("#edit-menu").val() + '&table=projects';
$.post('proj_query.php', datum, responseB);
function responseB(data) {
var jSON = $.parseJSON(data);
$("#id-blurb textarea").val(jSON.blurb);
}
}
});
}
});
When I test by running alerts, I get alerts right up until I add the callback function (the one called 'responseB'). Then it stops generating them. So it seems it's finding the document, and it seems to be accepting the data, but that's about it. After that nothing happens.
proj_query.php looks like this:
<?php
require_once ('../functions/functions.php');
connectDB('../functions/login.php');
require_once("session.php");
if(isset($_POST['shortname'])) {
$shortname = $_POST['shortname'];
$table = $_POST['table'];
$query = "SELECT title, medium, description, blurb FROM $table WHERE shortname='$shortname'";
$result = mysql_query($query);
$results = mysql_fetch_array($result, MYSQL_ASSOC);
print_r(json_encode($results));
}
?>
The HTML is this (but you may not need that):
<div id="change" class="grid_4">
<h3>Edit a Project</h3>
<form method="post" action="index.php" name="editform" onsubmit="return validateEdit(this);">
<input type="hidden" name="edit" value="yes" />
<div class="field_container"><label>Project Name:</label>
<select id="edit-menu" name="shortname">
<option value="">Select a Project...</option>
<?php //For creating the dropdown menu
$query = "SELECT * FROM projects ORDER BY title ASC";
$result = mysql_query($query);
if (!$result) die ("Server says: <br/>Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for($i=0; $i<$rows; $i++) {
$results[] = mysql_fetch_array($result, MYSQL_ASSOC);
$option = $results[$i]['title'];
$value = $results[$i]['shortname'];
echo "<option value=\"$value\">" . $option . "</option>\n";
}
?>
</select>
</div>
<div class="field_container"><label>Title:</label><input type="text" name="title" maxlength="128"/></div>
<div class="field_container"><label>Date:</label><input type="date" name="date" /></div>
<div class="field_container"><label>Medium:</label><input type="text" name="medium" maxlength="256"/></div>
<div class="field_container"><label>Dimmensions:</label><input type="text" name="description" maxlength="64"/></div>
<div class="field_container"><label>Area:</label><input type="text" name="area" maxlength="16"/></div>
<div class="field_container"><label>Video Number:</label><input type="text" name="video" maxlength="64"/></div>
<div class="field_container"><label>New Shortname:</label><input type="text" name="new_shortname" maxlength="16"/></div>
<div class="field_container" id="id-blurb"><label><a title="Click for old content">Work Blurb:</a></label><textarea class="blurb" name="blurb" rows="5" ></textarea></div>
<input class="submit" type="submit" value="Edit Project" />
</form>
</div>
Banging my head on this one...