I am trying to send 2 values from different parts of a page to the same ajax function. Basically, it's a search filter wherein selecting categories is one module and selecting brands is another both of which are attributes of a product and independent of each other.
I need 3 conditions where search is performed either
only if brand is selected or
only if cat is selected or
if both are selected.
My issue is 1 and 3 are working. but 2nd condition isn't as it takes the cat value as the brand. Please help me correct my function.
My AJAX function:
function filter(subid) {
alert(subid);
var brand_filter = new Array();
$("input:checked").each(function() {
brand_filter.push($(this).val());
});
$.ajax({
type: 'POST',
url: 'getSubcategoryProducts.php',
data: {
brand_filter:brand_filter,
subId: subid
},
success: function(data) {
//alert(data);
$('#productDetail').html(data).fadeIn('slow');
$('#sub_cat_menuItem a').addClass('.collection-category-brands li.active, .collection-category-brands li:hover');
}
});
}
Module of selecting brand:
<div class="collection-brands-filter">
<h4>Filter by Brands</h4>
<div class="brand-filter-form">
<form>
<?php $brandlist = $objBrands-> getAll("status=1");
foreach($brandlist as $branditem){
?>
<span><input type="checkbox" name="brand_filter[]" <?php if ('checked="checked"'){ ?> onClick="filter(<?php echo $branditem['id'];?>);" <?php } ?> value="<?php echo $branditem['id'];?>"/><?php echo $branditem['name'];?></span>
<?php } ?>
</form>
</div>
</div>
Module of selecting category:
<div class="collection-category-brands">
<ul>
<?php
//Fetching sub categories of the main_category
while($query2res = mysql_fetch_array($query2)){ ?>
<li id="sub_cat_menuItem"><?php echo $query2res['1'];?></li>
<?php $subId = $query2res['id'];}?>
</ul>
</div>
getSubcategoryProducts.php code:
<?php
include_once("class/site_root.php");
include('includes/connect.php');
include_once(DIR_ROOT."class/functions.php");
include_once(DIR_ROOT."class/products.php");
$objProducts = new products();
$subId = $_POST['subId'];
//IF ONLY BRAND IS SELECTED AND NOT SUB CATEGORY
if(isset($_POST['brand_filter'])&&!isset($_POST['subId']))
{
echo "only brand is selected";
foreach($_POST['brand_filter'] as $item)
{
$res = $objProducts->getAll('status=1 and brand_id='.$item);?>
<ul>
<?php foreach($res as $val){?>
<li>
<img src="<?php echo $val['img_small']; ?>" alt="icon"/>
<div class="collection-item-hover">
<div class="collection-category-detail">
Know More
<div class="collection-item-detail">
<h4><?php echo $val['product_name']; ?></h4>
<p><?php echo $val['descr_small']; ?></p>
</div>
</div>
</div>
</li>
<?php }?>
</ul>
<?php }
}
//IF ONLY SUB CATEGORY IS CHOSEN!
else if(isset($subId)&&!isset($_POST['brand_filter'])){
echo "only sub cat selected!";
$productsquery=mysql_query("SELECT products.product_name,products.id,products.main_id,
products.img_small,products.descr_small,sub_category.name
FROM products
LEFT JOIN sub_category on
products.sub_id=sub_category.id
WHERE sub_category.id=".$subId);
$count = mysql_num_rows($productsquery);
$subNameVal=mysql_fetch_array(mysql_query("select name from sub_category where id=".$subId));
?>
<h3><?php echo $subNameVal['name'];?></h3>
<?php
if($count>0)
{
?>
<ul>
<?php
while($productsRes=mysql_fetch_array($productsquery))
{
?>
<li>
<img src="<?php echo $productsRes['img_small']; ?>" alt="icon"/>
<div class="collection-item-hover">
<div class="collection-category-detail">
Know More
<div class="collection-item-detail">
<h4><?php echo $productsRes['product_name']; ?></h4>
<p><?php echo $productsRes['descr_small']; ?></p>
</div>
</div>
</div>
</li>
<?php }
?>
</ul>
<?php }
}
//IF BOTH ARE SELECTED
else //if(isset($_POST['brand_filter'])&&isset($subId))
{
echo "both selected!";
echo
"SUB-".$subId."<br/>";
foreach ($_POST['brand_filter'] as $item)
{
echo "brand-".$item."<br/>";
}
}
?>
Related
I have search webpage, but when the search is run, there is a blank first result.
<?php include "headnav.php";
$count = 0;
$sql = "SELECT * FROM lost_property";
if (!empty($_POST)) {
$name = mysqli_real_escape_string($dbconnect, htmlspecialchars($_POST['name']));
$item = mysqli_real_escape_string($dbconnect, htmlspecialchars($_POST['item']));
$area = mysqli_real_escape_string($dbconnect, htmlspecialchars($_POST['area']));
$sql = "
SELECT *
FROM lost_property
JOIN item
ON lost_property.itemID = item.itemID
JOIN area
ON lost_property.areaID = area.areaID
WHERE name LIKE '%$name%'
AND item LIKE '%$item%'
AND area LIKE '%$area%'
ORDER
BY lost_property.name ASC
";
$search_query = mysqli_query($dbconnect, $sql);
$count = mysqli_num_rows($search_query);
}
$result = $dbconnect->query($sql);
?>
<body>
<div class="form">
<h1>Search for lost property here:</h1>
<form action="" method="POST">
Name:
<input type="text" placeholder="Name" name="name">
Item type:
<select name="item" class="dropdown">
<option value="" disabled selected>Item</option>
<?php
$item_sql = "SELECT DISTINCT item FROM `lost_property`
JOIN item ON (lost_property.itemID = item.itemID)
ORDER BY item ASC
";
$item_query = mysqli_query($dbconnect, $item_sql);
$item_rs = mysqli_fetch_assoc($item_query);
do {
?>
<option value="<?php echo $item_rs['item']; ?>"><?php echo $item_rs['item']; ?></option>
<?php
} while ($item_rs = mysqli_fetch_assoc($item_query));
?>
</select>
Area (where it was found):
<select name="area" class="dropdown">
<option value="" disabled selected>Area</option>
<?php
$area_sql = "SELECT DISTINCT area FROM `lost_property`
JOIN area ON (lost_property.areaID = area.areaID)
ORDER BY area ASC
";
$area_query = mysqli_query($dbconnect, $area_sql);
$area_rs = mysqli_fetch_assoc($area_query);
do {
?>
<option value="<?php echo $area_rs['area']; ?>"><?php echo $area_rs['area']; ?></option>
<?php
} while ($area_rs = mysqli_fetch_assoc($area_query));
?>
</select>
<input type="submit" value="Search" name="btn">
</form>
</div>
<div class="gallery">
<h2>Search results:</h2>
<?php
//check for results. If there are none display error
if ($count < 1) {
?>
<div class="error">
<h1>No results were found.</h1>
</div>
<?php
} //end if
else {
do {
?>
<!-- display image and information from database and show in gallery -->
<div class="results">
<h3><?php echo $search_rs['name']; ?></h3>
<h3><?php echo $search_rs['item']; ?></h3>
<p><?php echo $search_rs['area']; ?></p>
</div>
<?php
} // end of do
while ($search_rs = mysqli_fetch_assoc($search_query));
} //end else
//if there are any display
?>
</div>
</table>
</body>
</html>
It's hard to see without any CSS, but no matter what is searched, there is always one result, but the h3 and p fields don't have any content. If there wasn't the no results error message it would pop up there too. What is causing this first result?
Use while (){}, if you use do instead it will run once first (credit to Magnus Eriksson).
It ends up like
else {
while ($search_rs = mysqli_fetch_assoc($search_query)) {
?>
<!-- display image and information from database and show in gallery -->
<div class="results">
<h3><?php echo $search_rs['name']; ?></h3>
<h3><?php echo $search_rs['item']; ?></h3>
<p><?php echo $search_rs['area']; ?></p>
</div>
<?php
} // end of do
} //end else
//if there are any display
?>
instead of
else {
do {
?>
<!-- display image and information from database and show in gallery -->
<div class="results">
<h3><?php echo $search_rs['name']; ?></h3>
<h3><?php echo $search_rs['item']; ?></h3>
<p><?php echo $search_rs['area']; ?></p>
</div>
<?php
} // end of do
while ($search_rs = mysqli_fetch_assoc($search_query));
} //end else
//if there are any display
?>
So I'm not sure if its my foreach loop or my sql query that needs fixing, but Ive tried grouping by "categoryname" to no avail. I want the category names ($qs['name']) to be displayed only once and all li belonging to that category displayed in it. Any help would be great.
What I have is this:
NEW HAMPSHIRE <--This is $state_name-->
Personal auto <--This is $qs['name']-->
• Your young drivers—help them play it safe
Personal auto <--This is $qs['name']-->
• The dangers of drunken driving
Personal auto <--This is $qs['name']-->
• How to keep your vehicle safe from car thieves
ETC....
And what I'm looinkg for is this:
NEW HAMPSHIRE <--This is $state_name-->
Personal auto <--This is $qs['name']-->
• Your young drivers—help them play it safe
• The dangers of drunken driving
• How to keep your vehicle safe from car thieves
ETC....
CODE:
$sql = mysql_query(
"SELECT qs, state, title, link, category, categoryid, categoryname
FROM `irc_consumer_content`
JOIN `irc_consumer_content_category`
ON irc_consumer_content.category=irc_consumer_content_category.categoryid
ORDER BY categoryname ASC;");
$row = mysql_fetch_assoc($sql);
$states_array = array( "AL"=>"Four-state topics",
"CT"=>"Connecticut topics",
"NH"=>"New Hampshire topics",
"NJ"=>"New Jersey topics",
"NY"=>"New York topics");
do {
$qs_array[$row['state']][] = array( "qs"=>$row['qs'],
"title"=>$row['title'],
"link"=>$row['link'],
"name"=>$row['categoryname']);
} while ($row = mysql_fetch_assoc($sql));
<div>
<h1>Topics available</h1>
<? //==== GET STATE ====================================
foreach ($states_array as $state => $state_name) { ?>
<h2><? echo $state_name; ?></h2>
<? //==== GET STATE TOPICS ======================
foreach ($qs_array[$state] as $i => $qs) { ?>
<h3><? echo $qs['name']; ?></h3>
<ul class="first-level">
<li class="list" id="<? echo $qs['qs']; ?>">
<div class="selected-list-item">
<div id="title-text">
<? echo iconv('Windows-1252', 'UTF-8', $qs['title']); ?>
</div>
<div class="ideas-div">
<div class="ideas-top">
</div>
<div class="idea-images">
</div>
<div class="ideas-bottom">
</div>
</div>
</div>
</li>
</ul>
<? } ?>
<? } ?>
</div>
CODE:(UPDATED)
<div>
<h1>Topics available</h1>
<? //==== GET STATE ====================================
foreach ($states_array as $state => $state_name) { ?>
<h2><? echo $state_name; ?></h2>
<? $category = "";?>
<? //==== GET STATE TOPICS ======================
foreach ($qs_array[$state] as $i => $qs) {
if ($category != $qs['name']){
$category = $qs['name'];
?>
<h3><? echo $category; //echo $qs['name']; ?></h3>
<ul class="first-level">
<li class="list" id="<? echo $qs['qs']; ?>">
<? }else { ?>
</li>
</ul>
<ul class="first-level">
<li class="list" id="<? echo $qs['qs']; ?>">
<? }?>
<!--ALL ELSE IS THE SAME-->
You can check if current category is the same with the previous one. So you can open and close the ul accordingly.
e.g.
<div>
<h1>Topics available</h1>
<? //==== GET STATE ====================================
foreach ($states_array as $state => $state_name) { ?>
<h2><? echo $state_name; ?></h2>
<?php $old_name = ''; ?>
<ul>
<? //==== GET STATE TOPICS ======================
foreach ($qs_array[$state] as $i => $qs) { ?>
<?php if ($old_name != $qs['name']) : ?>
<?php $old_name = $qs['name']; ?>
</ul><--Close previous item ul-->
</ul><--Open ul for new item-->
<?php endif; ?>
<h3><? echo $qs['name']; ?></h3>
<ul class="first-level">
<li class="list" id="<? echo $qs['qs']; ?>">
<div class="selected-list-item">
<div id="title-text">
<? echo iconv('Windows-1252', 'UTF-8', $qs['title']); ?>
</div>
<div class="ideas-div">
<div class="ideas-top">
</div>
<div class="idea-images">
</div>
<div class="ideas-bottom">
</div>
</div>
</div>
</li>
<? } ?>
</ul>
<? } ?>
</div>
Also keep in mind that mysql* functions are deprecated. Use PDO instead.
I have this and i think this is a code for block which displays releated products for the product in the product page here it is.
/template/catalog/product/list/releated_products.phtml :
<?php if($this->getItems()->getSize()): ?>
<div class="related-products">
<h2><?php echo $this->__('Related Products') ?></h2>
<ol class="products-grid row" id="block-related">
<?php foreach($this->getItems() as $_item): ?>
<li class="item span3">
<?php if(!$_item->isComposite() && $_item->isSaleable()): ?>
<?php endif; ?>
<div class="product"> <img src="<?php echo $this->helper('catalog/image')->init($_item, 'thumbnail')->resize(590,714) ?>" alt="<?php echo $this->htmlEscape($_item->getName()) ?>" />
<div class="product-details">
<p class="product-name"><?php echo $this->htmlEscape($_item->getName()) ?></p>
<?php echo $this->getPriceHtml($_item, true, '-related') ?>
<?php if ($this->helper('wishlist')->isAllow()) : ?>
<?php echo $this->__('Add to Wishlist') ?>
<?php endif; ?>
</div>
</div>
</li>
<?php endforeach ?>
</ol>
<script type="text/javascript">decorateList('block-related', 'none-recursive')</script>
<script type="text/javascript">
//<![CDATA[
$$('.related-checkbox').each(function(elem){
Event.observe(elem, 'click', addRelatedToProduct)
});
var relatedProductsCheckFlag = false;
function selectAllRelated(txt){
if (relatedProductsCheckFlag == false) {
$$('.related-checkbox').each(function(elem){
elem.checked = true;
});
relatedProductsCheckFlag = true;
txt.innerHTML="<?php echo $this->__('unselect all') ?>";
} else {
$$('.related-checkbox').each(function(elem){
elem.checked = false;
});
relatedProductsCheckFlag = false;
txt.innerHTML="<?php echo $this->__('select all') ?>";
}
addRelatedToProduct();
}
function addRelatedToProduct(){
var checkboxes = $$('.related-checkbox');
var values = [];
for(var i=0;i<checkboxes.length;i++){
if(checkboxes[i].checked) values.push(checkboxes[i].value);
}
if($('related-products-field')){
$('related-products-field').value = values.join(',');
}
}
//]]>
</script>
</div>
<?php endif ?>
So how i can display this block in my view.phtml which display the info for the product view page. I want to paste it bellow the product description.
Thanks in advance!
Try this https://magento.stackexchange.com/questions/3177/showing-related-products-in-product-view-page
Make sure your current product has related product.
I am trying to get the related products block to show up on my product detail page.
I have the folling code in the respective .phtml file
<?php
<?php echo "Related product block"?>
<?php if($this->getItems()->getSize()): ?>
<div class="block block-related">
<div class="block-title">
<strong><span><?php echo $this->__('Related Products') ?></span></strong>
</div>
<div class="block-content">
<p class="block-subtitle"><?php echo $this->__('Check items to add to the cart or') ?> <?php echo $this->__('select all') ?></p>
<ol class="mini-products-list" id="block-related">
<?php foreach($this->getItems() as $_item): ?>
<li class="item">
<?php if(!$_item->isComposite() && $_item->isSaleable()): ?>
<?php if (!$_item->getRequiredOptions()): ?>
<input type="checkbox" class="checkbox related-checkbox" id="related-checkbox<?php echo $_item->getId() ?>" name="related_products[]" value="<?php echo $_item->getId() ?>" />
<?php endif; ?>
<?php endif; ?>
<div class="product">
<img src="<?php echo $this->helper('catalog/image')->init($_item, 'thumbnail')->resize(50) ?>" width="50" height="50" alt="<?php echo $this->htmlEscape($_item->getName()) ?>" />
<div class="product-details">
<p class="product-name"><?php echo $this->htmlEscape($_item->getName()) ?></p>
<?php echo $this->getPriceHtml($_item, true, '-related') ?>
<?php if ($this->helper('wishlist')->isAllow()) : ?>
<?php echo $this->__('Add to Wishlist') ?>
<?php endif; ?>
</div>
</div>
</li>
<?php endforeach ?>
</ol>
<script type="text/javascript">decorateList('block-related', 'none-recursive')</script>
</div>
<script type="text/javascript">
//<![CDATA[
$$('.related-checkbox').each(function(elem){
Event.observe(elem, 'click', addRelatedToProduct)
});
var relatedProductsCheckFlag = false;
function selectAllRelated(txt){
if (relatedProductsCheckFlag == false) {
$$('.related-checkbox').each(function(elem){
elem.checked = true;
});
relatedProductsCheckFlag = true;
txt.innerHTML="<?php echo $this->__('unselect all') ?>";
} else {
$$('.related-checkbox').each(function(elem){
elem.checked = false;
});
relatedProductsCheckFlag = false;
txt.innerHTML="<?php echo $this->__('select all') ?>";
}
addRelatedToProduct();
}
function addRelatedToProduct(){
var checkboxes = $$('.related-checkbox');
var values = [];
for(var i=0;i<checkboxes.length;i++){
if(checkboxes[i].checked) values.push(checkboxes[i].value);
}
if($('related-products-field')){
$('related-products-field').value = values.join(',');
}
}
//]]>
</script>
The echo above the code shows up on my page. Which of course proves that i implemented the block correctly.
Just everything in the if-statement doesn't show.
I spend some time looking for solutions and i tried rebuilding the indexes and my related product is visible on the frontend.
Anyone know how i can fix this?
Magento will always return a low number or 0 for the condition:
$this->getItems()->getSize()
if some/all of the related products are in the user's cart, and consequently items will appear as though they are missing.
To prevent this behaviour, duplicate the core Magento 'Related' class:
/app/code/core/Mage/Catalog/Block/Product/List/Related.php
to local:
/app/code/local/Mage/Catalog/Block/Product/List/Related.php
Then comment out the following lines in the if statement:
if (Mage::helper('catalog')->isModuleEnabled('Mage_Checkout')) {
//mod - show all related products, even if they have been added to the cart
//Mage::getResourceSingleton('checkout/cart')->addExcludeProductFilter($this->_itemCollection,
// Mage::getSingleton('checkout/session')->getQuoteId()
//);
$this->_addProductAttributesAndPrices($this->_itemCollection);
}
On your 4 line:
<?php if($this->getItems()->getSize() > 0 ? true : false) ?>
Try it.
At the top of your code type
var_dump($this->getItems()->getSize()) // does this print NUll, False or > 0
If the code above print NULL or false or less than 1, then do
print_r($this->getItems());
If none of the above print the information you expected then check your block getItems() method
Also where is the closing IF for if($this->getItems()->getSize()):
I have have a website where there are multiple products, the user can add one to their cart and get on screen feedback via ajax that the basket updated.
However on certain products this does not work below is the code that gets used.
THE PHP
function updateBasket()
{
$this->load->model('Checkout_model');
$this->load->model('Product_model');
$derivativeId = $this->input->post('selDerivative-1');
$quantity = $this->input->post('selQuantity');
$derivative = $this->Product_model->GetProducts(array('pdId' => $derivativeId), 'small');
// Add item to shopping bag.
$attributes = $this->Product_model->GetProductDerivatives(array('pdId' => $derivativeId));
$this->Checkout_model->AddProduct($derivative, $attributes, $quantity);
$this->data['message'] = 'Item added to Shopping Bag.';
// Update Delivery Price
$this->Checkout_model->updateDelivery(49);
$this->data['items'] = $this->Checkout_model->GetProducts();
$this->template
->build('checkout/quickbasket', $this->data);
}
THE HTML FEEDBACK
<?php
//var_dump($items);
//print_r($this->session->userdata);
?>
<div id="basketoverview">
<div id="quickbasket">
<h1><?php echo $this->cart->total_items(); ?> item in bag</h1>
<?php foreach ($items as $item) : ?>
<div class="item">
<img src="<?php echo base_url().$item['imageUrl'];?>" alt="<?php echo $item['imageAlt'];?>" width="70"/>
<h4><?php echo $item['imageAlt'];?></h4>
<span class="price">£<?php echo $item["price"]; ?></span>
<span class="qauntity">Quantity: <?php echo $item['qty']; ?></span>
</div>
<?php endforeach; ?>
</div>
<div id="basket_options">
VIEW BAG / CHECKOUT
</div>
</div>
** THE AJAX SCRIPT**
$("#frmProducts").submit(function(){
var dataSet = $("#frmProducts").serialize();
$.ajax({
url: "<?php echo base_url();?>products/updateBasket",
data: dataSet,
type: "POST",
success: function(data){
$('html, body').animate({scrollTop:0}, 'slow');
$("#miniCart").load("<?php echo base_url();?>checkout/loadCartView");
$('body').append(data);
$('#basketoverview').fadeIn(2000);
setTimeout(function () { $('#basketoverview').fadeOut(2000).hide(); }, 8000);
}
});
return false;
});
A SUCCESSFUL POST
selDerivative-1 171
selQuantity 1
submitted 1
** AN UNSUCCESSFUL POST **
selDerivative-1 223
selQuantity 1
selURL-1 colonial/dining/prestige-dining-for-six
submitted 1
The frmProducts form
<?php echo form_open(current_url(), array('id' => 'frmProducts'), array('submitted' => '1')); ?>
<div class="formRow">
<label for="rattanType"><?php echo $product_attribute_names; ?> </label><br />
<?php
$options = array();
foreach ($product_derivatives as $derivative) :
$options[$derivative['derivativeId']] = $derivative['attributeValues'];
endforeach;
?>
<?php echo form_dropdown('selDerivative-1', $options, $product_details->pdId, 'class="select clear" id="selDerivative-1"'); ?>
</div>
<?php if (count($individual_products) > 0) : ?>
<div class="formRow">
<label for="itemType">Item</label><br />
<select class="select clear" id="selURL-1" name="selURL-1">
<option value="<?php echo current_url(); ?>">Full Set</option>
<?php foreach ($individual_products as $product) : ?>
<option value="<?php echo site_url($product->fullProductPath); ?>"><?php echo $product->productTitle; ?> - £<?php echo ($product->productSavingType != 'none' ? $product->productSavingPrice : $product->productPrice); ?></option>
<?php endforeach; ?>
</select>
<input id="btnGo-1" name="btnGo-1" type="submit" value="GO" />
</div>
<?php endif; ?>
<div class="formRow">
<label for="addQty">Quantity</label><br />
<?php
$options = array();
for ($i = 1; $i < 10; $i++) :
$options[$i] = $i;
endfor;
?>
<?php echo form_dropdown('selQuantity', $options, '1', 'class="small select clear"'); ?>
</div>
<input type="submit" value="add to bag" name="btnAddToBag" id="btnAddToBag" />
<?php echo form_close(); ?>
I have absolutly why the first post would get added to the basket and the second would not, does any one have any idea from looking at my code?
This is kind of a longshot, but I have the suspicion that you have a session problem. The CI Session manager has a few issues randomly creating new sessions from Ajax calls. The issue and some solutions are discussed here:
http://codeigniter.com/forums/viewthread/186070/