How Do i Loop Js with mysql while loop - javascript

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))

Related

Using jQuery to check a box generated from php

I am attempting to 'check' the the 'AC:Front' box from a button click on the below website. I tried changing the checkbox to 'checked' and I also tried changing the encompassing to class="checked".
The goal is to eventually collect the inputted VIN, run it through a decoder and use the data to fill the page.
Here is the website
HTML
<div class="stm-single-feature">
<div class="heading-font">Comfort</div>
<div class="feature-single">
<label>
<input type="checkbox" value="A/C: Front" name="stm_car_features_labels[]"/>
<span>A/C: Front</span>
</label>
</div>
CSS
div.checker span.checked {
background-position: -16px 0; }
PHP
<?php
if ($items) {
if (!empty($id)) {
$features_car = get_post_meta($id, 'additional_features', true);
$features_car = explode(',', $features_car);
} else {
$features_car = array();
}
foreach ($items as $item) { ?>
<?php if(isset($item['tab_title_single'])): ?>
<div class="stm-single-feature">
<div class="heading-font"><?php echo $item['tab_title_single']; ?></div>
<?php $features = explode(',', $item['tab_title_labels']); ?>
<?php if (!empty($features)): ?>
<?php foreach ($features as $feature): ?>
<?php
$checked = '';
if (in_array($feature, $features_car)) {
$checked = 'checked';
};
?>
<div class="feature-single">
<label>
<input type="checkbox" value="<?php echo esc_attr($feature); ?>"
name="stm_car_features_labels[]" <?php echo $checked; ?>/>
<span><?php echo esc_attr($feature); ?></span>
</label>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
<?php endif; ?>
<?php }
}?>
JavaScript
<script type="text/javascript">
jQuery(function($) {
$("#generateVin").on("click", function() {
var $checkbox = $("input[type=checkbox]").eq(1);
$checkbox.prop("checked", true);
$checkbox.parent().addClass("checked");
});
});
</script>

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";
}
?>

Get input before submitting to insert into action url

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));

Object doesn't support property or method 'remove'

I know there is some issue with get document.getElementById and IE, but not sure why IE is having a problem with .remove and all other browsers are not. Any help here would be appreciated. I am getting the error
SCRIPT438: Object doesn't support property or method 'remove'
from the error console. The Javascript works in all other browsers.
Here is the code:
<script type="text/javascript"><!--
function removeModule() {
<?php $tab = 1; ?>
var module_row = <?php echo $module_row; ?>;
if(!confirm('Are you sure?'))
{
return false;
}
var x = 1;
while (x < module_row)
{
if (document.getElementById('tab-' + x).checked)
{
document.getElementById('tab-' + x).remove();
document.getElementById('module-' + x).remove();
document.getElementById('tab-module-' + x).remove();
}
x++;
<?php $tab++; ?>
}
$('#form').submit();
}
//--></script>
This is from an opencart module, it is the tpl file. I've included part of the file here as well so hopefully someone can spot whatever the error is.
<?php echo $header; ?>
<div id="content">
<div class="breadcrumb">
<?php foreach ($breadcrumbs as $breadcrumb) { ?>
<?php echo $breadcrumb['separator']; ?><?php echo $breadcrumb['text']; ?>
<?php } ?>
</div>
<?php if ($error_warning) { ?>
<div class="warning"><?php echo $error_warning; ?></div>
<?php } ?>
<div class="box">
<div class="heading">
<h1><img src="view/image/module.png" alt="" /> <?php echo $heading_title; ?></h1>
<div class="buttons">
<a onclick="$('#form').submit();" class="button"><?php echo $button_save; ?></a>
<a onclick="removeModule();" class="button"><?php echo $button_delete ?></a>
<a onclick="location = '<?php echo $cancel; ?>';" class="button"><?php echo $button_cancel; ?></a></div>
</div>
<div class="content">
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form">
<div class="vtabsQS">
<?php $module_row = 1; ?>
<?php foreach ($modules as $module)
{ ?>
<div style="margin-left: -7px; float:left;">
<input type="checkbox" style="float: left; margin-top: 8px;" id="tab-<?php echo $module_row; ?>" onClick="" value="#tab-<?php echo $module_row; ?>" />
<a href="#tab-module-<?php echo $module_row; ?>" id="module-<?php echo $module_row; ?>">
<?php foreach ($languages as $language)
{ ?>
<label class="inputLrgTab"><?php if (!empty($module['language_id'][$language['language_id']])) { echo $module['language_id'][$language['language_id']];} ?></label>
<?php } ?>
</a><br />
</div>
<?php $module_row++; ?>
<?php } ?>
<span id="module-add" style="clear: both; margin-left: -7px;"><?php echo $button_add_module; ?> <img src="view/image/add.png" alt="" onclick="addModule();" /></span>
</div>
<?php $module_row = 1; ?>
<?php foreach ($modules as $module) { ?>
<div id="tab-module-<?php echo $module_row; ?>" class="vtabs-content" style="margin-left:230px;">
<table class="form">
<tr>
<td><?php echo $entry_title; ?></td>
<td class="left">
<?php foreach ($languages as $language) { ?>
<img src="view/image/flags/<?php echo $language['image']; ?>" alt="<?php echo $language['name']; ?>" />
<input class="inputLrg" type="text" name="<?php echo $classname; ?>_module[<?php echo $module_row; ?>][language_id][<?php echo $language['language_id']; ?>]" value="<?php if (!empty($module['language_id'][$language['language_id']])) { echo $module['language_id'][$language['language_id']];} ?>">
<br />
<?php } ?>
<span class="error"><?php echo $error_title; ?></span>
</td>
</tr>
<tr>
<td><?php echo $entry_limit; ?></td>
You should get the parent of the element you are trying to remove and use the remove child method to find and remove the element
element.parentNode.removeChild(element);
this works in all browsers including IE.
remove() as a method on HTMLElements unfortunately is not supported by Internet Explorer.
You could use the workaround in this SO answer for a vanilla javascript solution.
However as you already seem to use jQuery, instead replace
document.getElementById('tab-' + x).remove();
with
$('#tab-' + x).remove();
You should use this
element.parentElement.removeChild(element);
Supported by all browser and also have some benefits over just a hack to
remove child element.
Here is another workaround for keep using .remove() function
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = this.length - 1; i >= 0; i--) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
And then you can remove elements like this
document.getElementById("my-element").remove();
or
document.getElementsByClassName("my-elements").remove();
Here is Stack Overflow link for further info also source of this answer.
It appears that IE10 also throws this error..
Here one way I tried using the objects outerHTML property:
if(typeof document.getElementById('id').remove=='function'){
//If support is found
document.getElementById('id').remove()
}
else{
//If not
document.getElementById('id').outerHTML='';
}
You can polyfill the remove() method:
(function (arr) {
arr.forEach(function (item) {
if (item.hasOwnProperty('remove')) {
return;
}
Object.defineProperty(item, 'remove', {
configurable: true,
enumerable: true,
writable: true,
value: function remove() {
this.parentNode.removeChild(this);
}
});
});
})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);

doesn't work .buttonset() on jQuery

I have a number of :checkbox elements that are initialized by a wordpress.
Now i set .buttonset() function to #format but this is not work...
like this sample:http://jqueryui.com/button/#checkbox
HTML:
<div id="format">
<?php
$categories = get_categories();
foreach ($categories as $category) { ?>
<input type="checkbox" name="check" value="<?php echo $category->cat_ID; ?>">
<label><?php echo $category->cat_name;?></label><?php } ?>
</div>
JS:
$('#format').buttonset();
$('input[type=checkbox]').removeClass('ui-helper-hidden-accessible');
$(':checkbox[name=check]').each(function( i ){
var nameID = 'check'+ (i+1);
this.id = nameID;
$(this).next('label').prop('for', nameID);
});
All your checkboxes has the same name "check".
Try to do this:
<div id="format">
<?php
$i = 0;
$categories = get_categories();
foreach ($categories as $category) { ?>
<input type="checkbox" name="check<?php echo $i ?>" value="<?php echo $category->cat_ID; ?>">
<label><?php echo $category->cat_name;?></label>
<?php
$i++;
}
?>
</div>
Then in your js:
$(':checkbox[name^=check]').each(function( i ){
var nameID = 'check'+ (i+1);
this.id = nameID;
$(this).next('label').prop('for', nameID);
});
Then jQuery will find all checkboxes that start with name check, like "check1", "checkblabla", etc...
And the "$('#format').buttonset();" needs to come after the "for" change.
Fonts:
http://api.jquery.com/attribute-starts-with-selector/
Edited:
I think you dont really need to change the for with js, you can do that only with php, then:
<div id="format">
<?php
$i = 0;
$categories = get_categories();
foreach ($categories as $category) { ?>
<input type="checkbox" name="check<?php echo $i ?>" value="<?php echo $category->cat_ID; ?>">
<label for="check<?php echo $i ?>"><?php echo $category->cat_name;?></label>
<?php
$i++;
}
?>
</div>
Then in your js:
$( "#format" ).buttonset();

Categories

Resources