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 } ?>
Related
i have a form in php in which i am trying to add multiple fields on button click, i did the following code:
function add_fields() {
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
';
objTo.appendChild(divtest)
}
<div id="room_fileds">
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
</div>
<input type="button" id="more_fields" onclick="add_fields()" value="Add More" />
however this is not working, i am getting the following error:
** Uncaught ReferenceError: add_fields is not defined
at HTMLInputElement.onclick **
can anyone please tell me what is wrong in here, thanks in advance
As per the comment previously about cloning content and appending that the following goes a step further and uses a content Template to store the content that you wish to add with each button click. This template could hold the generated select menu and would be invisible until added to the DOM. This means you do not have a huge, bloated function that gets called - only some quite simple code to find the template, create a clone and append to the designated parent node.
The below example has the PHP commented out so that the display here looks OK but would need the PHP code re-enabled to produce the actual results you need. None of the code within the template has an ID attribute so there is no need to worry about duplicating IDs.
const clonetemplate=(e)=>{
let parent=document.getElementById('room_fields');
let tmpl=document.querySelector('template#rfc').content.cloneNode( true );
parent.append( tmpl )
}
// Button click handler
document.querySelector('input#add').addEventListener('click',clonetemplate );
// pageload... display initial menu
clonetemplate();
#room_fields > div{margin:1rem;padding:1rem;border:1px solid grey;font-family:monospace;}
#room_fields > div label{display:block;width:80%;padding:0.25rem;margin:0.1rem auto;float:none;}
#room_fields > div select,
#room_fields > div input{float:right}
<div id="room_fields">
<!-- add content here -->
</div>
<input type="button" id='add' value="Add More" />
<!--
Generate the content once that will be repeated
and keep it within a content template until
needed.
-->
<template id='rfc'>
<div>
<div class='form-group col-md-6'>
<label>Item
<select class='form-control' name='item'>
<option>Select Item
<!-- Uncomment this PHP for live version
<?php
$sql = 'select * from `inventory` order by `categoryname` asc';
$res = $con->query( $sql );
$group=array();
while( $rs=$res->fetch_object() ){
$group[ $rs->categoryname ]=$rs;
}
foreach( $group as $key => $values ){
printf('<optgroup label="%s">',$key);
foreach( $values as $obj )printf( '<option>%s',$obj->name );
print('</optgroup>');
}
?>
-->
<option>Hello
<option>World
<option>No IDs
<option>Simples...
</select>
</label>
</div>
<div class='form-group col-md-6'>
<label>Weight
<input name='weight' type='text' class='form-control' placeholder='Weight' />
</label>
</div>
</div>
</template>
In the string that you define in the function add_fields and assign to divtest.innerHTML you have line breaks. You probably also get an error when loading the script saying that you have a syntax error. You should try to avoid line breaks in strings. An alternative solution could be to use backticks for your string. YOu can read about it here: Template literals (Template strings).
Here are two examples. The first fails with both syntax and reference error, the next works fine (but does not do anything).
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = '
test
';
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = `
test
`;
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />
I have a div which contains a button(Book it).When I press the button I want to add to the current url the id of the item I clicked on.Then get that id to pop up a box with clicked item data without refreshing the page, because I need to pop up in the current page.
Here it gets the treatments Id
<div class="treatments">
<ul>
<?php
global $treatments;
foreach($treatments as $treatment){
echo ' <li>'.$treatment['name'].'</li>';
};
?>
</ul>
<div class="line"></div>
</div>
<div class="treatment-items">
<?php
global $iController;
$items;
if(isset($_GET['treatmentID'])){
$items = $iController->getItemByTreatmentId($_GET['treatmentID']);
}else{
$items = $iController->getItemByTreatmentId(4);
}
foreach($items as $item){
echo '
<div class="col-30 items">
<div>
<p>'.$item['id'].'</p>
<img src="'.$item['img_url'].'" alt="'.$item['name'].'" />
<h3>'.$item['name'].'</h3>
<p>'.$item['time'].' min</p>
<p>'.$item['price'].'$</p>
<input type="hidden" id="hidden_input" name="id_item" value="'.$item['id'].'">
<a class="bookBtn" id="btn"><button>BOOK IT</button></a> // when I press this button I want that box to pop up
</div>
</div>
';
}
?>
</div>
Pop up box
<div class="bookDetails">
<div class="details">
<?php
global $iController;
$itemm;
if(isset($_GET['id_item'])){
$itemm = $iController->getItemById($_GET['id_item']);
}
echo'
<h1>Book your treatment</h1>
<p>Treatment Name : '.$itemm['name'].'</p>
<p>Treatment Time :'.$itemm['time'].' </p>
<p>Treatment Price : '.$itemm['price'].'</p>
';
?>
<form action="" method="POST">
<label for="date">Choose your date:</label>
<input type="date" for="date" name="date"><br>
<input type="submit" value="Cancel" id="cancel">
<input type="submit" value="Book Now">
</form>
Jquery code
$(".bookBtn").click(function(){
$(".bookDetails").show();
})
getItemById function
public function getItemById($id){
$sql="SELECT * FROM treatments_item WHERE id=$id";
echo $id;
$items = mysqli_query($this->connection,$sql);
$returnArray = array();
if($items){
while($row = mysqli_fetch_assoc($items)){
array_push($returnArray, $row);
}
return $returnArray[0];
}else{
echo'It doesn't work';
}
}
You can use ajax or mix php and javascript like this:
<script>
$(document).ready(function() {
<?php session_start(); ?>//Remove session_start
if (!<?php $_GET(['id'])?'true':'false'; ?>) {
alert something
} else {
something ..
}
});
</script>
hope this was helpful. :)
<div class="treatment-items">
<?php
global $iController;
$items;
if(isset($_GET['treatmentID'])){
$items = $iController->getItemByTreatmentId($_GET['treatmentID']);
}else{
$items = $iController->getItemByTreatmentId(4);
}
foreach($items as $item){
echo '
<div class="col-30 items">
<div>
<p>'.$item['id'].'</p>
<img src="'.$item['img_url'].'" alt="'.$item['name'].'" />
<h3>'.$item['name'].'</h3>
<p>'.$item['time'].' min</p>
<p>'.$item['price'].'$</p>
<input type="hidden" class="id_item" value="'.$item['id'].'">
<div class="bookBtn"><button>BOOK IT</button></div> // when I press this button I want that box to pop up
</div>
</div>
';
}
?>
Note: Never use id same name in one Page i.e., id="hidden_input" // In for loop same name will be generated. It will create bug down the line. Same goes for Input name, instead use class.
$(document).ready(function(){
$('body').on('click','.bookBtn',function(){
var treatmentID = $(this).siblings('.id_item').val();
// $(this) --> it will read the data of the property you have clicked
// .siblings --> adjacent class with name ('.id_item')
$.ajax({
url: 'treatments.php',
type: "get", //send it through get method
data: {
treatmentID: treatmentID
},
success: function(response) {
//operation to show the data in div
//e.g., $('#divId').html(data.name);
$(".bookDetails").show();
}
});
})
})
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.
So i am haveing this page where it is displaying articles andunderneet each article it will have a textarea asking allowing the user to insert a comment.I did the AJAX and it works fine.Some of the validation works fine aswell(Meaning that if the textarea is left empty it will not submit the comment and display an error).The way i am doing this validation is with the ID.So i have multi forms with the same ID.For the commets to be submited it works fine but the validtion doesnt work when i go on a second form for exmaple it only works for the first form
AJAX code
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('#comment');
if (comment.val().length > 1)
{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
else
{
alert("Hello");
}
});
});
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" >
<label>New Comment</label>
<textarea id="comment" name="comment" class="comment"></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Again the problem being is the first form works fine but the second one and onwaord dont work properly
try this:
var comment = $('.comment',form);
instead of
var comment = $('#comment');
That way you're targeting the textarea belonging to the form you're validating
ps.
remove the id's from the elements or make them unique with php, all element id's should be unique
I am working on a web site which displays some data that is retrieved from a database using php. Now, there are also other chekcboxes, which are included in a form. Based on the user input on these checkboxes, i wanted the div displaying the data to reload. For example, after a user checks one of the boxes and clicks apply, the div displaying should recompute the results. I realise that the form data must be passed onto an ajax function. Which would convert this form data into a json object and send it across to a php file. The php file can then access the form variables using $_POST['var']. I hope i have got the theory correct. Nevertheless, i have a number of problems during execution.
Firstly, the php code that deals with the form variables in on the same page as the form. I want to know how to direct the form data from the ajax function to this code.
Secondly, the ajax function is getting executed alright, the form is getting submitted, the page isn't reloading (as desired) but however, I am not able to access the submitted variables in the php code.
Here is my code:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('#filter_form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'index.php',
data: $('#filter_form').serialize(),
success: function () {
alert('form was submitted');
}
});
e.preventDefault();
});
});
</script>
<div style="float: left;margin-left: -175px;" class="box2">
<h2>Filter by :</h2>
<form id="filter_form" name="filter_form" href="#">
<!--<form id="filter_form" name="filter_form" action="<?php echo $_SERVER['PHP_SELF'];?>" method ="post" href="#">-->
<h3>Location</h3>
<?php
//Get all the distinct values for filter. For example, Get all the locations available, display them in a container. Similarly for the party type as well. Connect to to the database once, get all these values,
//store them in arrays and use the arrays to display on screen.
$query = "Select LOCATION, PARTY_TYPE, GENRE, HAPPY_HOURS, OUTDOOR_ROOFTOP from venue_list order by HAPPY_HOURS";
$result = mysqli_query($con,$query);
$filter_array = array(5);
for($i=0; $i<5; $i++){
$filter_array[$i] = array();
}
while($row = mysqli_fetch_array($result)){
array_push($filter_array[0],$row['LOCATION']);
array_push($filter_array[1],$row['PARTY_TYPE']);
array_push($filter_array[2],$row['GENRE']);
array_push($filter_array[3],$row['HAPPY_HOURS']);
array_push($filter_array[4],$row['OUTDOOR_ROOFTOP']);
}
for($i=0; $i<5; $i++){
$filter_array[$i] = array_unique($filter_array[$i]);
}
?>
<ul>
<?php
foreach($filter_array[0] as $location){
?>
<li>
<input type="checkbox" id="f1" name="location[]" value="<?php echo $location?>" <?php if (isset($_POST['location'])){echo (in_array($location,$_POST['location']) ? 'checked' : '');}?>/>
<label for="f1"><?php echo $location?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Party Type</h3>
<ul>
<?php
foreach($filter_array[1] as $party_type){
?>
<li>
<input type="checkbox" id="f2" name="party_type[]" value="<?php echo $party_type?>" <?php if (isset($_POST['party_type'])){echo (in_array($party_type,$_POST['party_type']) ? 'checked' : '');}?>/>
<label for="f2"><?php echo $party_type?></label>
</li>
<?php
}
?>
</ul>
<br><h3>Genre</h3>
<ul>
<?php
foreach($filter_array[2] as $genre){
?>
<li>
<input type="checkbox" id="f3" name="genre[]" value="<?php echo $genre?>" <?php if (isset($_POST['genre'])){echo (in_array($genre,$_POST['genre']) ? 'checked' : '');}?>/>
<label for="f3"><?php echo $genre?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Happy Hours</h3>
<ul>
<?php
foreach($filter_array[3] as $happy_hours){
?>
<li>
<input type="checkbox" id="f4" name="happy_hours[]" value="<?php if($happy_hours){ echo $happy_hours;} else {echo "Dont Bother";} ?>" <?php if (isset($_POST['happy_hours'])){echo (in_array($happy_hours,$_POST['happy_hours']) ? 'checked' : '');}?>/>
<label for="f4"><?php echo $happy_hours?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Outdoor/Rooftop</h3>
<ul>
<?php
foreach($filter_array[4] as $outdoor_rooftop){
?>
<li>
<input type="checkbox" id="f5" name="outdoor_rooftop[]" value="<?php echo $outdoor_rooftop?>" <?php if (isset($_POST['outdoor_rooftop'])){echo (in_array($location,$_POST['outdoor_rooftop']) ? 'checked' : '');}?>/>
<label for="f5"><?php echo $outdoor_rooftop?></label>
</li>
<?php
$i=$i+1;
}
?>
</ul>
<br><br><br>
<div id="ContactForm" action="#">
<input name="filter_button" type="submit" value="Apply" id="filter_button" class="button"/>
</div>
<!--
<h2>Sort by :</h2>
<input type="radio" id="s1" name="sort" value="Name" <?php if (isset($_POST['sort'])){echo ($_POST['sort'] == 'Name')?'checked':'';}?>/>
<label for="f1"><?php echo 'Name'?></label>
<input type="radio" id="s1" name="sort" value="Location" <?php if (isset($_POST['sort'])){echo ($_POST['sort'] == 'Location')?'checked':'';}?>/>
<label for="f1"><?php echo 'Location'?></label>
<br><br><br>
<input name="filter_button" type="submit" value="Apply" id="filter_button" class="button"/>
-->
</form>
</div>
<div class="wrapper">
<h2>Venues</h2>
<br>
<div class="clist" id="clublist" href="#">
<?php
?>
<table id = "venue_list">
<tbody>
<?php
//Functions
//This function builds the query as every filter attribute is passed onto it.
function query_builder($var_name){
$append = strtoupper($var_name)." in (";
$i=0;
foreach($_POST[$var_name] as $array){
$append = $append."'{$array}'";
$i=$i+1;
if($i < count($_POST[$var_name])){
$append = $append.",";
}
else{
$append=$append.")";
}
}
return $append;
}
//We first need to check if the filter was set in the previous page. If yes, then the query needs to be built with a 'where'. If not the query will just display all values.
//We also need to check if order by is required. If yes, we will apply the corresponding sort, else we will just sort on the basis of location.
//The below 2 variables do the same.
$filter_set = 0;
$filter_variables = array('location','party_type','genre','happy_hours','outdoor_rooftop');
$map_array = array();
if(isset($_POST['location'])){
$filter_set = 1;
}
if(isset($_POST['party_type'])){
$filter_set = 1;
}
if(isset($_POST['genre'])){
$filter_set = 1;
}
if(isset($_POST['happy_hours'])){
$filter_set = 1;
}
if(isset($_POST['outdoor_rooftop'])){
$filter_set = 1;
}
if($filter_set == 1){
$query = "Select * from venue_list where ";
$append_query=array(5);
$j=0;
foreach($filter_variables as $var){
if(isset($_POST[$var])){
$append_query[$j] = query_builder($var);
$j=$j+1;
}
}
$h=0;
//Once all the individual where clauses are built, they are appended to the main query. Until then, they are stored in an array from which they are
//sequentially accessed.
foreach($append_query as $append){
$query=$query.$append;
$h=$h+1;
if($h < $j){
$query=$query." AND ";
}
}
}
else{
$query = "Select * from venue_list";
}
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
$name = $row['NAME'];
$img = $row['IMAGE_SRC'];
$addr = $row['ADDRESS'];
$location = $row['LOCATION'];
echo "<script type='text/javascript'>map_function('{$addr}','{$name}','{$img}');</script>";
?>
<tr>
<td>
<img src="<?php echo $img.".jpg"?>" height="100" width="100">
</td>
<td>
<?php echo $name?>
</td>
<td style="display:none;">
<?php echo $location?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<br>
</div>
All the 3 components are part of index.php. Kindly notify me if the code is unreadable or inconvenient I will edit it. Awaiting a solution. Thank you.
in this case change your javascript code to
var submiting = false;
function submitmyforum()
{
if ( submiting == false )
{
submiting = true;
$.ajax({
type: 'post',
url: 'index.php',
data: $('#filter_form').serialize(),
success: function () {
alert('form was submitted');
submiting = false;
}
});
}else
{
alert("Still working ..");
}
}
and change the form submit button to
<input name="filter_button" type="button" onclick="submitmyforum();" value="Apply" id="filter_button" class="button"/>
don't forget to change submit button type="submit" to type="button"