Get input before submitting to insert into action url - javascript

Im trying to get a value of an input into my buttons action url before the button is pushed.
I need to get the value of:
id="qty<?php echo $i;?>"
Into where it says:
<?php echo VALUE OF $qtyforaction; ?>
My Code is:
<?php $i = $_product->getId();?>
<form action="<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId()?>"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
<input type="text" name="qty" id="qty<?php echo $i;?>" maxlength="12" value="1" title="Qty" class="cartnum" />
<?php $qtyforaction = 'qty'.$i; ?>
<?php echo $qtyforaction; ?>
<button type="button" class="addtocartbutton button btn-cart" onclick="setLocation('<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>qty/<?php echo VALUE OF $qtyforaction; ?>')" ><span><span>Order Again</span></span></button>
</form>
Would I have to use javascript to get it into the url string? My javascript is a bit ropey, would something like this work?
<script type="text/javascript">
var something= document.getElementById('<?php echo $qtyforaction;?>');
</script>
UPDATE WITH FULL CODE:
<?php
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
/* Get the customer data */
$customer = Mage::getSingleton('customer/session')->getCustomer();
/* Get the customer's email address */
$customer_email = $customer->getEmail();
}
$collection = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_email', array(
'like' => $customer_email
));
$uniuqProductSkus = array();
foreach ($collection as $order) {
$order_id = $order->getId();
$order = Mage::getModel("sales/order")->load($order_id);
$ordered_items = $order->getAllItems();
foreach ($ordered_items as $item)
{
if (in_array($item->getProduct()->getSku(), $uniuqProductSkus)) {
continue;
} else {
array_push($uniuqProductSkus, $item->getProduct()->getSku());
$_product = Mage::getModel('catalog/product')->load($item->getProductId());
$product_small_image_path = Mage::helper('catalog/image')->init($_product, 'small_image')->resize(200);
$product_thumbnail_path = Mage::helper('catalog/image')->init($_product, 'small_image')->resize(150);
$summaryData = Mage::getModel('review/review_summary')->load($item->getProductId());
echo "<li>";
echo "<div class='previous-name'><p><a style='color:black; font-weight:bold; font-size:14px;' href='" . $_product->getProductUrl() . "'>";
echo $item->getName() . "</a></p></div>";
echo "<div class='previous-image'><a href='" . $_product->getProductUrl() . "'>";
echo "<img src='" . $product_small_image_path . "' />";
echo "</a></div>";
echo "<div class='previous-rating'>";
echo "<p><a style='color:black; font-weight:bold; font-size:14px;' href='" . $_product->getProductUrl() . "#product_tabs_review_tabbed'>Review this beer now</a></p>";
echo $summaryData->getRatingSummary() . '% Would buy again <br/>';
echo "<div class='rating-box' style='float:left;'>";
echo "<div class='rating' style='width:" . $summaryData->getRatingSummary() . "%'></div></div>";
echo "</div>";
/**echo "<div class='previous-button'>";
echo '<button type="button" title="Add to Cart" class="button btn-cart" onclick="setLocation(\'';
echo $this->helper('checkout/cart')->getAddUrl($_product);
echo '\')"><span><span>Order Again</span></span></button>';
echo "</div>";**/
?>
<?php $i = $_product->getId();?>
<div class='previous-button'>
<form action="<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId()?>"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
<input type="text" name="qty" id="qty<?php echo $i;?>" maxlength="12" value="1" title="Qty" class="cartnum" />
<?php $qtyforaction = 'qty'.$i; ?>
<script type="text/javascript">
var xy = document.getElementsByTagName("input")[0].getAttribute("qty");
var x = "<button type='button' class='addtocartbutton button btn-cart' onclick='setLocation()'><span><span>Order Again</span></span></button>";
document.getElementById("buttonaddcart").innerHTML = x;
</script>
<div id="buttonaddcart">
<button type="button" class="addtocartbutton button btn-cart" onclick="setLocation('<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>qty/')" ><span><span>Order Again</span></span></button>
</div>
</form>
</div>
<?php
echo "<div class='previous-clear'></div>";
echo "</li>";
}
}
}
?>

You need to get the value of the id attribute:
var x = document.getElementsByTagName("input")[0].getAttribute("id");
But how do you plan on using PHP to echo out this variable if PHP is loaded and done with before Javascript even comes into play? You could use Javascript though to display this variable on the page if that's all you needed.
If you had something in your HTML to target, you could do it like this:
document.getElementById("result").innerHTML = x;
But anyways, get the action attribute value...
var y = document.getElementsByTagName("form")[0].getAttribute("action");
Then set the action attribute to this + the qty...
document.getElementsByTagName("form")[0].setAttribute("action", x + y);
That should work for you, if not, try wrapping x + y in additional parentheses...("action", (x + y));

Related

Passing Hidden ID value to another page using javascript php

I am trying to pass hidden value from page to another page and it work fine only for first record however for other records it's showing error
Here is the code:
$sql = "SELECT id,jdes,title FROM job";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<input type="hidden" id="hidden_user_id" value="<?php echo $row["id"] ?>">
<h3><?php echo $row["title"] ?>:</h3>
<p class="lead">
<?php echo $row["jdes"] ?>
</p>
<button type="button" id="requestthis" class="btn btn-primary">
Request
</button>
<?php
}
} else {
echo "Nothing to display Yet";
}
?>
jobs-inner.php
<?php
echo $_GET['hidden_id'];
?>
Javascript:-
$(function() { //ready function
$('#requestthis').on('click', function(e){ //click event
e.preventDefault();
var hidden_id = $('#hidden_user_id').val();
var url = "jobs-inner.php?hidden_id="+hidden_id;
window.location.replace(url);
})
})
Error:-
Undefined index: hidden_id in C:\wamp64\www\project\jobs-inner.php on line 3
It might be a simple problem but I am a beginner and I can't figure it out.
Your value is unique but the id isn't. Make the id of the input unique something like below.
<input type="hidden" id="hidden_user_<?php echo $row["id"] ?>" value="<?php echo $row["id"] ?>">
but you would have to do a count on code below to make it display base on how many rows you have.
<?php
echo $_GET['hidden_id'];
?>
Without JavaScript
$sql = "SELECT id,jdes,title FROM job";
$result = $conn->query($sql);
$count = 1;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<input type="hidden" id="hidden_user_<?php echo $count ?>" value="<?php echo $row["id"] ?>">
<h3><?php echo $row["title"] ?>:</h3>
<p class="lead"><?php echo $row["jdes"] ?></p>
<form id="<?php echo $count ?>" action="jobs-inner.php?hidden_id=<?php echo $row["id"] ?>" method="post">
<input type="submit" vaule="Request">
</form>
<?php
$count++;
}
} else {
echo "Nothing to display Yet";
}
?>

Buttons having different id to call the same js function

foreach ($_SESSION['songlist']['items'] as $key => $value1) {
$id = $value1['id']['videoId'];
session_start();
$_SESSION['id'] = $id;
echo "<br>";
echo "<iframe src='//www.youtube.com/embed/$id?enablejsapi=1' frameborder='0' allowfullscreen id='video'></iframe>";echo "<br>";
echo '<div id="Added" style="display:none;">ADDED!</div>';
echo "<form id='demo' method='POST' action=''><button type='button' name='button' id='$id' method='POST' onclick='Count($id)'>Add to playlist</button></form>";
}
This is my button
I want to have a separate counter for different buttons using js onclick function.

How to post the information using javascript for a preview table

Hey I need to know how to post the information to another php page using javascript to provide a preview table.
Here's my HTML that has a onchange tag that sends the productID to the function.
<form action="Home.php" method="Post">
<div>
<p>
<span class="text">Please Select a product:</span>
<select id="Select_Product" name="Select_Product" onchange="productInfo(this.value)" class="select">
<?php
//setting the select statement and running it
$search = "SELECT * FROM Library.Products order by Name";
$return = mysql_query($search);
//echo "<select id=Select_Product name=Select_Product onchange=productInfo(this.value) class=select>";
while ($row = mysql_fetch_array($return)) {
echo "<option value='" . $row['ProductID'] . "' selected='selected'>".$row['Name'] . "</option>";
}
?>
</select>
</p>
<table>
<tr>
<td>
<input name="action" type="submit"class="button" id="button_Add" value="Add"/>
</td>
<td>
<input name="action" type="submit" class="button" id="button_Remove" value="Remove"/>
</td>
<td>
<input name="action" type="submit" class="button" id="button_empty" value="Empty"/>
</td>
</tr>
</table>
</div>
From there I want it to send it to catalogue.php.
<script>
function productInfo(key) {
//Send key to catalogue.php
}
</script>
If I can get the other page to get that variable I can run a MYSQL command to get the information. Here is what catalogue.php looks like at the moment.
<?php
$sql = "SELECT Name, Price FROM Library.Products WHERE ProductID = " . $product_id;
echo "<table border=\"1\" padding=\"3\" width=\"650px\"><tr><th>Name</th><th>Description</th><th>Price</th><th width=\"80px\">Image</th></tr>";
echo "<tr>";
echo "<td>" .$product_id . "</td>";
echo "<td> Hi</td>";
echo "<td></td>";
echo "<td align=\"center\"><img alt=\"\" src=\"productImages/".$product_id.".jpg\ width=\"120\" height=\"120\"/></td>";
echo "</tr>";
echo "</table><br>";
document.
?>
So in a sense I want to turn the key in productInfo(key) to be assigned to the variable $product_id in catalogue.php. Thanks for helping.
You can add an invisible form :
<script>
function productInfo(key) {
//Send key to catalogue.php
document.getElementById( "key" ).value = key;
document.getElementById( "frm" ).submit(); // SUBMIT FORM.
}
</script>
<form action="catalogue.php" method="post" id="frm"
style="display:none" target="_blank">
<input type="text" id="key" name="key"/>
</form>
catalogue.php needs one little change :
<?php
$product_id = $_POST[ "key" ]; //<================== VALUE FROM THE INVISIBLE FORM.
$sql = "SELECT Name, Price FROM Library.Products WHERE ProductID = " . $product_id;
echo "<table border=\"1\" padding=\"3\" width=\"650px\"><tr><th>Name</th><th>Description</th><th>Price</th><th width=\"80px\">Image</th></tr>";
echo "<tr>";
echo "<td>" .$product_id . "</td>";
echo "<td> Hi</td>";
echo "<td></td>";
echo "<td align=\"center\"><img alt=\"\" src=\"productImages/".$product_id.".jpg\ width=\"120\" height=\"120\"/></td>";
echo "</tr>";
echo "</table><br>";
document.
?>
Or you can use Ajax :
html file
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax ( key ) {
$.ajax( { type : 'POST',
data : { 'param' : key },
url : 'catalogue.php',
success: function ( data ) {
document.getElementById( "my_div" ).innerHTML = data;
},
error: function ( data ) {
alert( "error" );
}
});
}
function productInfo( key ) {
//Send key to catalogue.php
myAjax( key );
}
</script>
</head>
<body>
<button onclick="productInfo('123')">Click here to get the data</button>
<div id="my_div">
- data will show here -
</div>
</body>
</html>
catalogue.php
<?php
$key = $_POST[ "param" ];
echo "<table border='1'>" .
" <tr>" .
" <td>$key</td>" .
" <td>ABC</td>" .
" </tr>" .
"</table>";
?>

Remove particular row by clicking remove link present in the same row

I have form 1st page(test.php) as follows
<form method="post" action="newtest.php">
<input name="product[]" type="checkbox" value="1" <?php if(in_array("1", $session_products)) echo "checked='checked'"; ?> alt="1607.00" />
<input name="product[]" type="checkbox" value="2" <?php if(in_array("2", $session_products)) echo "checked='checked'"; ?> alt="1848.00" />
<input name="product[]" type="checkbox" value="3" <?php if(in_array("3", $session_products)) echo "checked='checked'"; ?> alt="180.00" />
<input name="product[]" type="checkbox" value="4" <?php if(in_array("4", $session_products)) echo "checked='checked'"; ?> alt="650.00" />
<input name="product[]" type="checkbox" value="5" <?php if(in_array("5", $session_products)) echo "checked='checked'"; ?> alt="495.00" />
<div class="ph-float">
<input type="submit" name="button" value="Checkout >>" class="ph-button ph-btn-green fm-submit" disabled="true" >
</div>
</form>
Based on checkbox selection am displaying Book name,Amount and total in a table as follows(newtest.php)
(Remember am not using data base, these values are not comming from data base instad am taking these values from
product array as specified below)
<?php
$product = array();
$product[1] = array('name' => "Text Book of Human Anatomy by B.D.Chaurasiavol 6th edition Vol -I Vol-II Vol-III.", 'price' => 1607);
$product[2] = array('name' => "Nettars Atlas of Anatomy", 'price' => 1848);
$product[3] = array('name' => "Genera Anatomy by B.D.Chaurasia", 'price' => 180);
$product[4] = array('name' => "Inderbir Singh Embryology 10th edition ", 'price' => 650);
$product[5] = array('name' => "Inderbir Singh Histology ", 'price' => 495);
if(isset($_POST['button']))
{
$first = array();
$second = array();
foreach ($_POST['product'] as $pId)
{
$first[] = $product[$pId]['name'];
$second[] = $product[$pId]['price'];
}
$bookauthor = count($first);
$bookprice = count($second);
$max = ($bookauthor > $bookprice ? $bookauthor : $bookprice);
echo '<br />';
echo '<i style="font-color:#000000;font-weight:bold;text-decoration:underline;font-size:21px; padding-left:110px;margin-top:10px"> List of books you have selected:</i>';
echo '<table>';
echo '<tr>';
echo '<th style="text-align: center">SL No.</th>';
echo "<th>Book Name</th>";
echo "<th>Amount in INR</th>";
echo "<th>Action</th>";
echo '</tr>';
$count = 0;
for ($i = 0; $i < $max; $i++)
{
$count++;
echo '<tr>';
echo "<td style='text-align: center'>{$count}</td>";
echo "<td>{$first[$i]}</td>";
echo "<td>{$second[$i]}</td>";
echo "<td><a href='#'><i style='color:#F5F5F5;background:#D52020'>REMOVE</i> </a></td>";
echo '</tr>';
}
$total = array_sum($second);
echo '<tr>';
echo "<td colspan='2' style='font-weight:bold;font-size:14px'>Total Amount</td>";
echo "<td style='font-weight:bold;font-size:14px;'>{$total}</td>";
echo "</tr>";
echo '</table>';
}
?>
I want to remove particular row from table when i click on REMOVE link displaying in a same row, how to achive this?
link is ok or should i have to use button.If any one write some code may helpfull as am new webie...
Thanks in advance.
$('i').click(function(){
$(this).parent('a').parent('td').parent('tr').remove();
});
The row is deleted but as clicking makes you follow the link, it's immediately restored when the page is refreshed.
Add return false; or event.preventDefault(); at the end of the callback to prevent the default behavior :
$(document).ready(function() {
$("#favoriteFoodTable .deleteLink").on("click",function() {
var tr = $(this).closest('tr');
tr.css("background-color","#FF3700");
tr.fadeOut(400, function(){
tr.remove();
});
return false;
});
});

How Do i Loop Js with mysql while loop

Hey Guys i need to ask is that how can i loop the javascript with the while loop
As My code is this
$i=0;
while($row = mysqli_fetch_array($result)) {
echo '<div class="grid_1_of_4 images_1_of_4" >
<form method="post" action="......">
<a class = "popup-link" href = "'.$row['shade_enlarged_img'].'" alt = "" title = "'.$row['shade_desc'].'">
<img src="'.$row['shade_img'].'" alt="" title = "click to enlarge"/> </a>
<h2>'.$row['shade_desc'].'</h2>
<p style="font-size:0.95em"><b>Code: '.$row['shade_code'].'</b></p>
<p>Category: '.$row['categories'].'</p>';
$code=$row['shade_code'];
$result_quantity = mysqli_query($con,"SELECT ...........);
$num_of_rows=mysqli_num_rows($result_quantity);
$count=0;?>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint<?php echo $i; ?>").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "getprice.php?brand=<?php echo $row['brand_name']; ?>&category=<?php echo $row['categories'];?>&q="+str;
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint<?php echo $i; ?>").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script> <?php
echo '<p style="font-size:0.71em">Available Packaging: <select name="product_qty" onchange="showUser(this.value)" style="margin-left:4px; font-size:1.02em;">
<option value=""></option>';
while($row_quantity = mysqli_fetch_array($result_quantity)) {
echo '<option value="'.$row_quantity['quantity'].'">'.$row_quantity['quantity'].' '.$row_quantity['quantity_unit'].'</option>';
}
echo '</select></p>';
echo '<div id="txtHint'.$i.'"><b>Person info will be listed here.</b></div>';
echo '</p>';
echo '<p style="font-size:0.71em">Quantity: <input type="number" style="display:inline; width:50px;" name="number_of_units" min="1"></p>';
echo '<button class="button"><span class="cart-button"><img src="images/cart.jpg" alt="" />Add to Cart</span> </button>
<input type="hidden" name="product_code" value="'.$row['shade_code'].'" />
</form>
</div>'; $i++;
the Code Works Well but as i'm calling all the items by while loop from mysqldatabase so when i run this code this only works on the 1st item and rest does'nt work..
Watch This Images For A Quick Veiw http://imgur.com/2qM0FzX
I think you will have a problem with #products because you can't have the same id="products" over and over again otherwise the jQuery doesn't know which to switch. Actually, same with #priceInput. Try adding the auto-incrementing $i as demonstrated below.
<?php
$i = 0;
while($row = mysqli_fetch_array($result)) { ?>
<div class="grid_1_of_4 images_1_of_4" >
<form method="post" action="page.php">
<a class = "popup-link" href = "<?php echo $row['shade_enlarged_img']; ?>" alt = "" title = "<?php echo $row['shade_desc']; ?>">
<img src="<?php echo $row['shade_img']; ?>" alt="" title = "click to enlarge"/> </a>
<h2><?php echo $row['shade_desc']; ?></h2>
<p style="font-size:0.95em"><b>Code: <?php echo $row['shade_code']; ?></b></p>
<p>Category: <?php echo $row['categories']; ?></p>
<script>
$(function () {
$('#products<?php echo $i; ?>').change(function () {
$('#priceInput<?php echo $i; ?>').val($('#products<?php echo $i; ?> option:selected').attr('data-price'));
});
});
</script>
<p style="font-size:0.71em">Available Packaging: <select id="products<?php echo $i; ?>" name="product_qty" style="margin-left:4px; font-size:1.02em;" onChange="ShowInfo('<?php echo $i; ?>','<?php echo $row['brand_name']; ?>','<?php echo $row['categories']; ?>')">
<?php
$code = $row['shade_code'];
$result_quantity = mysqli_query($con,"SELECT ............");
$num_of_rows = mysqli_num_rows($result_quantity);
$count = 0;
while($row_quantity = mysqli_fetch_array($result_quantity)) { ?>
<option value="<?php echo $row_quantity['quantity']; ?>" data-price="<?php echo $row_quantity['price']; ?>"><?php echo $row_quantity['quantity'].' '.$row_quantity['quantity_unit']; ?></option><?php
} ?>
</select></p>
<div id="txtHint<?php echo $i; ?>"><b>Person info will be listed here.</b></div>
Price :<input type="text" name="price" value="" id="priceInput<?php echo $i; ?>" disabled="disabled"/>
<p style="font-size:0.71em">Quantity: <input type="number" style="display:inline; width:50px;" name="number_of_units" min="1"></p>
<button class="button"><span class="cart-button"><img src="images/cart.jpg" alt="" />Add to Cart</span> </button>
</form>
</div><?php
$i++;
} ?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script>
function ShowInfo(IdNum,RowBrand,RowCat) {
// Get the value of the selected dropdown
var SelVal = $('#products'+IdNum).val();
$.ajax({
type : 'GET',
url:"getprice.php?brand="+RowBrand+"&category="+RowCat+"&q="+SelVal;
success: function(result){
$('#txtHint'+IdNum).html(result);
}
});
}
</script>
Try the .= which will continue to add the latest results from you mysqli_fetch_array query.
Then just echo that summed up value you assigned to $just_a_variable out to the page or back to ajax etc.
<?php
$just_a_variable = '';
$just_a_variable .= '<p style="font-size:0.71em">Available Packaging: <select id="products" name="product_qty" style="margin-left:4px; font-size:1.02em;">';
while($row_quantity = mysqli_fetch_array($result_quantity)) {
$just_a_variable .= '<option value="'.$row_quantity['quantity'].'" data-price="'.$row_quantity['price'].'">'.$row_quantity['quantity'].' '.$row_quantity['quantity_unit'].'</option>';
}
$just_a_variable .= '</select></p>';
$just_a_variable .= ' Price :<input type="text" name="price" value="'.$row_quantity['price'].'" id="priceInput" disabled="disabled"/>';
echo $just_a_variable;
?>
that is because the mysql_fetch_array function returns one row at a time. If you want all the rows you should iterate over the results
$row = mysqli_fetch_array($result_quantity);
$total = mysql_num_rows($variable_resultfrom_sql_query);
while($row = mysql_fetch_array($variable_resultfrom_sql_query))

Categories

Resources