How to display images based on selecting ids.While adding portfolio images i am inserting data into two tables as portfolio table and portfolio_tags table.
I am having three tables portfolio,tags and portfolio_tags.
portfolio
=============
portfolio_id image_path
1 image.png
2 imag.png
3 images.png
4 img.png
5 imagess.png
Tags table:
==========
tag_id tag_name
1 All
2 CMS
3 DESIGN
portfolio_tag
=============
portfolio_id tag_id portfolio_tag_id
1 1 1
1 2 2
2 3 3
3 1 4
I will be fetching all the tags data as well as the portfolio data.While opening the page it will display all the data related to all the tags.But when we select particular only the information related to that tag to be displayed.
Ex:If i select CMS it should display only that information relation to CMS and if i select DESIGN only the information related to that tag should be displayed.
Can any one suggest me how to do that.
Here is my code.
Controller:
public function index()
{
$this->load->model('portfolio_model');
$data["records2"] = $this->portfolio_model->get_portfolio();
$data["records3"] = $this->portfolio_model->get_tags();
$data['mainpage'] = "portfolio";
$this->load->view('templates/template',$data);
}
Model:
function get_portfolio($limit, $start)
{
$this->db->limit($limit, $start);
$this->db->Select('portfolio.*');
$this->db->From('portfolio');
$this->db->where(array('portfolio.status'=>1));
$q=$this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
function get_tags()
{
$this->db->Select('tags.*');
$this->db->From('tags');
$q=$this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
View:
<?php $this->load->view('tagss');?>
<?php
$cnt = 0;
if(isset($records2) && is_array($records2)):?>
<?php foreach ($records2 as $r):?>
<div class="portfolioimages">
<img src="<?php echo base_url();?>admin/images/portfolio/thumbs/<?php echo $r->image_path;?>" />
</div>
<?php
if(($cnt%3) == 0) { echo "<br>"; }
$cnt++;
endforeach; endif;?>
Tags
<?php if(isset($records3) && is_array($records3)):?>
<?php foreach ($records3 as $r):?>
<div class="materials">
<div class="class453">
<?php echo $r->tag_name;?>
</div>
</div>
<?php endforeach ;endif;?>
<script type="text/javascript">
$('.materials a').not('.materials a:first').addClass('opacty');
$('.materials a').click(function(e){
$('.materials a').not(this).addClass('opacty');
$(this).removeClass('opacty');
});
</script>
For showing filtered images on clicking different tagNames, we can use ajax. So at first we need to create a new function in the Controller class which would display the fetched images url for the tag_id as the json object.
Add the function below to you controller.
public function tag_data($id){
$this->load->model('portfolio_model');
$data = array();
$tagged_result = $this->portfolio_model->get_tag_images($id); // call to model function
$tagged_images = array();
foreach($tagged_result as $tag){
$tagged_images[] = $tag->image_path;
}
echo json_encode($tagged_images);
}
In the code above I've called the function get_tag_images($id) which fetches all the images url from the database which are related to the tag_id.
Append the code below to the model class
public function get_tag_images($id){
$query = $this->db->select('image_path')->from('portfolio_tag')->join('portfolio',"portfolio_tag.portfolio_id = portfolio.portfolio_id")->where("tag_id", $id)->group_by('portfolio.portfolio_id')->get();
if($query->num_rows() > 0)
return $query->result();
else
return false;
}
Now we have to make some changes in the tags view.
View:
<?php
$cnt = 0;
if(isset($records2) && is_array($records2)):?>
<div id="portfolio">
<?php foreach ($records2 as $r):?>
<div class="portfolioimages">
<img src="<?php echo base_url();?>admin/images/portfolio/thumbs/<?php echo $r->image_path;?>" />
</div>
<?php
if(($cnt%3) == 0) { echo "<br>"; }
$cnt++;
endforeach; ?>
</div>
<?php endif;?>
Edit Tags view:
<?php if(isset($records3) && is_array($records3)):?>
<?php foreach ($records3 as $r):?>
<div class="materials">
<div class="class453">
<a href="javascript:void(0)" class="read_more12">
<span style="display:none"><?php echo $r->tag_id; ?></span> // this contains the tag_id
<?php echo $r->tag_name;?>
</a>
</div>
</div>
<?php endforeach ;endif;?>
Ajax -
<script type="text/javascript">
$('.materials div a').click(function(e){
e.preventDefault();
var tagId = $(this).find('span').html();
var url = '<?php echo base_url('portfolio/tag_data/'); ?>'+ tagId;
var $this = $(this);
$.ajax({
type: 'POST',
url: url,
data: {'tagid': tagId},
success: function(data){
var taggedImgs = $.parseJSON(data);
var inc = 0;
var unTag = [];
var portfolioImages = $('.portfolioimages a img').map(function(){
var url = $(this).attr('src').split('/');
return url[url.length-1];
});
$('.portfolioimages a img').each(function(e){
imgUrl = $(this).attr('src').split('/');
var imgPath = imgUrl[imgUrl.length-1];
// compare the tagged image with portfolio images url
if($.inArray(imgPath, taggedImgs) == -1){
// image doesn't matched
$(this).remove();
}
});
jQuery.each(taggedImgs, function(idx, tagImg){
var flag = false;
if($.inArray(tagImg, portfolioImages) == -1){
// image doesn't exist
$('#portfolio').append("<div class='portfolioimages'><a href='<?php echo base_url('index.php/portfolio'); ?>' target='_blank'><img src='<?php echo base_url('admin/images/portfolio/thumbs/'); ?>/"+tagImg+"'></a></div>");
}
});
},
error: function(err){
alert("Some error occured! "+ err);
}
})
})
</script>
Related
I have a script which loads several pages (views/home.php, views/about.php, views/contact.php etc):
$(document).ready(function() {
$('#content').load('views/home.php');
$('ul#nav li a').click(function(e) {
var pageq = $(this).attr('href');
$('#content').load('views/' + pageq + '.php');
document.title = $(this).attr('rel');
//to get the ajax content and display in div with id 'content'
$.ajax({
url:'views/'+pageq+'.php',
success: function(data){
$('#content').html(data);
}
});
//to change the browser URL to 'pageq'
if(pageq!=window.location){
window.history.pushState({path:pageq},'',pageq);
}
return false;
});
});
But it works only with html, for ex. <h1>Home</h1>.
Now I would add some variables to this pages. For example in setup.php there's a variable $page. How to display <h1>$page['title']</h1> ?
I tried with include('config/setup.php'); but it doesn't work.
I also tried this in my .js file: $.get('config/setup.php', { x : y });, but I don't know how to pass this variables and what is the best approach.
EDIT - navigation:
<?php
try{
$pdo = new PDO("mysql:host=localhost;dbname=mysite", 'root','root');
}
catch(PDOException $e) {
echo $e->getMessage();
}
$sql = "SELECT * FROM posts ORDER BY id";
$stmt = $pdo->prepare($sql);
$stmt->execute();
?>
<ul class="nav navbar-nav" id="nav">
<?php
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$sub_sql = "SELECT * FROM submenu WHERE cat_id=:id";
$sub_stmt = $pdo->prepare($sub_sql);
$sub_stmt->bindParam(':id',$row->id,PDO::PARAM_INT);
$sub_stmt->execute();
?>
<li class="dropdown <?php selected($path['call_parts'][0], $row->slug, 'active') ?>"><?php echo $row->title; ?>
<?php
if($sub_stmt->rowCount()) {
?>
<ul class="dropdown-menu" role="menu">
<?php
while ($sub_row = $sub_stmt->fetch(PDO::FETCH_OBJ)) {
?>
<li><?php echo $sub_row->sub_name; ?></li>
<?php
}
?>
</ul>
<?php
}
?>
</li>
<?php
}
?>
</ul>
make sure you have "json" in your jQuery ajax statement
php:
$myVar = $_POST['myVar'];
echo json_encode(array( "var_1"=>$var1, "var_2"=>$var2 ));
javascript:
var myVar = 'xyz';
$.post('config/setup.php', { myVar:myVar }, function(data) {
var var_1 = data.var_1,
var_2 = data.var_2; //<< matches w/ php above
}, "json");
I want to display custom option price with name in price box in product detail page.
I also try this link but not getting success this is link i use
So please suggest me any solution.
first of all you have to put button calculateprice
then onclick of calculateprice you have to call function chkprice()
function chkpice()
{
var a=document.getElementById("options_1_text").value;
var b=document.getElementById("options_2_text").value;
var c=document.getElementById("options_3_text").value;
var d=document.getElementById("options_4_text").value;
var e=<?php echo $_product = $this->getProduct()->getPrice()?>;
var f=(a+b+c+d)+e;
var e=document.getElementById(('product-price-'+<?php echo $_product = $this->getProduct()->getId()?>)).innerHTML;
$('product-price-'+<?php echo $_product = $this->getProduct()->getId()?>).innerHTML =''+e.replace(<?php echo $_product = $this->getProduct()->getPrice()?>,d)+'</span>';
}
insted of options_1_text,options_2_text,options_3_text,options_4_text put your id it will get your result
First you do the function that takes care of updating the charges:
function updateCharges(){
var tmpText="";
$("input[type='select']").each(function{
tmpText+=$("#"+this.id+"option:selected").text()+"<br>";
});
$("#detailDiv").html(tmpText)
}
Then you just bind the selects to that function
$("input[type='select']").change(updateCharges)
Now you just have to make sure to include in your template a <div id="detailDiv"></div>
I would just create a custom block with the above code and place it inside the product detail page. Also you should check the selectors used, they will look for absolutelty ALL selects on the page, so thats not what you may want. But its just a matter of firebug-ging untill the aproppiate selector is found
Recently I need something similar. Perhaps it is helpful for you.
Block class:
class Foo_Bar_Block_Baz extends Mage_Catalog_Block_Product_View {
protected function getOptionDataCollection($options) {
$optionDataCollection = array();
foreach ($options as $option) {
$optionDataCollection[$option->getData('option_id')] = array_filter($option->getData());
}
return $optionDataCollection;
}
protected function getOptionValueDataCollection($options) {
$optionValueDataCollection = array();
foreach ($options as $option) {
$optionType = $option->getType();
if ($optionType == 'drop_down') {
$optionValues = $option->getValues();
foreach ($optionValues as $valueItem) {
// here you could also use the option_type_id (in my case I needed the sku)
$optionValueDataCollection[$valueItem->getData('sku')] = array_filter($valueItem->getData());
}
} else {
//Mage::throwException('Unexpected input. Processing for this optionType is not implemented');
}
}
return $optionValueDataCollection;
}
public function getOptionsJson() {
$data = array(
'options' => array(),
'optionValues' => array()
);
$options = $this->getProduct()->getOptions();
array_push($data['options'], $this->getOptionDataCollection($options));
array_push($data['optionValues'], $this->getOptionValueDataCollection($options));
$optionsJson = json_encode($data);
return $optionsJson;
}
}
Template
<script id="optionsJson" type="application/json">
<?php echo $this->getOptionsJson(); ?>
</script>
JS
var json = JSON.parse(document.getElementById("optionsJson").innerHTML),
options = json.options[0],
optionValues = json.optionValues[0];
optionValues['<optionValueSKU>'].default_title
optionValues['<optionValueSKU>'].price
-----------Create controller-------------
<?php
class Magento_Guys_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
echo "Thank you !";
}
public function genCartAction()
{
$id = $this->getRequest()->getParam('pid');
$_product = Mage::getModel('catalog/product')->load($id);
$buy = Mage::helper('checkout/cart')->getAddUrl($_product);
echo $qty = (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty();
//echo $id;
//echo $this->getRequest()->getParam('id');;
}
}
?>
----------------Change Add to cart code-------------------
<?php if ($_product->isAvailable()): ?>
<b class="available_quanity" style="display: none">Available Quantity :</b> <span id="simplestock" class="simplestock">Please select a color to view the quantity</span>
<?php endif; ?>
</div>
<?php if(!$_product->isGrouped()): ?>
<div class="qty">
<label for="qty"><?php echo $this->__('Qty:') ?></label>
<?php $i = 0; ?>
<select id="qty" class="input-text" name="qty" style="width:50px;">
<?php while($i<=(int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty()):?>
<option value="<?php echo $i; ?>"><?php echo $i++; ?></option>
<?php endwhile; ?>
</select>
</div>
<?php endif; ?>
----------------Add Ajax for get Quantity---------------
<script>
jQuery(document).ready(function() {
jQuery(".product-options select[id^='attribute']").on('change', function() {
var id = getSimpleProductId();
var qty = "";
jQuery('.available_quanity').show();
jQuery("#fancybox-loading").show();
jQuery.ajax({
type: "POST",
data: 'pid=' + id,
url:'https://www.thewirelesscircle.com/guys/index/genCart',
success:function(response){
if (response) {
qty = response;
var x = document.getElementById("qty");
var i;
removeOptions(x);
for(i=1;i<=qty;i++) {
var option = document.createElement("option");
option.text = i;
option.value = i;
x.add(option);
}
}
jQuery("#fancybox-loading").hide();
}
});
});
});
</script>
---------------Get Selected Option Id in Magento-------------------
<script type="text/javascript">
function removeOptions(selectbox)
{
var i;
for(i = selectbox.options.length - 1 ; i >= 0 ; i--)
{
selectbox.remove(i);
}
}
function getSimpleProductId() {
var productCandidates = [];
jQuery.each(spConfig.settings, function (selectIndex, select) {
var attributeId = select.id.replace('attribute', '');
var selectedValue = select.options[select.selectedIndex].value;
jQuery.each(spConfig.config.attributes[attributeId].options, function(optionIndex, option) {
if (option.id == selectedValue) {
var optionProducts = option.products;
if (productCandidates.length == 0) {
productCandidates = optionProducts;
} else {
var productIntersection = [];
jQuery.each(optionProducts, function (productIndex, productId) {
if (productCandidates.indexOf(productId) > -1) {
productIntersection.push(productId);
}
});
productCandidates = productIntersection;
}
}
});
});
return (productCandidates.length == 1) ? productCandidates[0] : null;
}
</script>
Open page: app\code\core\Mage\Catalog\Block\Product\View\Options.php find protected function _getPriceConfiguration($option) function and add $data['title'] = $option->getTitle(); before return $data; statement.
Now, open app\design\frontend\YOUT_TEMPLATE_PATH\default\template\catalog\product\view\options.phtml
Add <div id="optiontitle"></div> top of the page.
Then find this:
$A(element.options).each(function(selectOption){
if ('selected' in selectOption && selectOption.selected) {
if (typeof(configOptions[selectOption.value]) != 'undefined') {
curConfig = configOptions[selectOption.value];
}
}
});
Replace by:
$A(element.options).each(function(selectOption){
if ('selected' in selectOption && selectOption.selected) {
if (typeof(configOptions[selectOption.value]) != 'undefined') {
curConfig = configOptions[selectOption.value];
optionTitle = curConfig.title + "<br>";
$("optiontitle").insert(optionTitle);
}
}
});
Hey I've created a sortable list for the backend of my site to organize my categories and I have it all working so it runs an update SQL statement with Ajax and it saves my data without a reload, but the order number that I'm displaying in my backend from the database doesn't change until I reload, any help would be great, thanks in advance!
PHP
<?php
$sql = "SELECT cat_id, cat_name, cat_slug, cat_status, cat_order, sta_id, sta_name
FROM app_categories LEFT JOIN app_status
ON app_categories.cat_status = app_status.sta_id
ORDER BY cat_order ASC";
if($result = query($sql)){
$list = array();
while($data = mysqli_fetch_assoc($result)){
array_push($list, $data);
}
foreach($list as $i => $row){
?>
<div class="row" id="page_<?php echo $row['cat_id']; ?>">
<div class="column two"><?php echo $row['cat_name']; ?></div>
<div class="column two"><?php echo $row['cat_slug']; ?></div>
<div class="column two"><?php echo $row['cat_status']; ?></div>
<div class="column two"><?php echo $row['cat_order']; ?></div>
</div>
<?php
}
}
else {
echo "FAIL";
}
?>
jQuery with Ajax call
$(document).ready(function(){
$("#menu-pages").sortable({
update: function(event, ui) {
$.post("ajax.php", { type: "orderPages", pages: $('#menu-pages').sortable('serialize') } );
}
});
});
And my ajax.php which does my update
<?php
parse_str($_POST['pages'], $pageOrder);
foreach ($pageOrder['page'] as $key => $value) {
$sql = "UPDATE app_categories SET `cat_order` = '$key' WHERE `cat_id` = '$value'";
if(query($sql)) {
echo "YES";
}
else {
echo "NO";
}
}
?>
You don't appear to have any kind of code for handling the front-end update. The easiest thing to do would be to add a callback in your ajax post and have the server send back the update information as json data.
So ajax.php would look more like
<?php
parse_str($_POST['pages'], $pageOrder);
foreach ($pageOrder['page'] as $key => $value) {
$sql = "UPDATE app_categories SET `cat_order` = '$key' WHERE `cat_id` = '$value'";
if(query($sql)) {
$orderSql = "SELECT cat_id, cat_name, cat_slug, cat_status, cat_order, sta_id, sta_name
FROM app_categories LEFT JOIN app_status
ON app_categories.cat_status = app_status.sta_id
ORDER BY cat_order ASC";
if($result = query($sql)){
echo json_encode(mysqli_fetch_assoc($result));
return;
}
} else {
echo json_encode( array('result' => 'failure'));
}
}
(Yeah, it's ugly and untested but you get the idea.)
Your javascript would then look something like
$.post("ajax.php", { type: "orderPages", pages: $('#menu-pages').sortable('serialize') }, function(res){
if (typeof res.result !== undefined && res.result === 'failure'){
alert('failed!');
return;
} else {
$.each(res, function(i, item){
$("#page_" + item.cat_id).find('div:eq(3)').html(item.cat_order);
});
}, 'json' );
Which again is terrible, but hopefully conveys the point.
Alternatively you could simply update the number in the sort div whenever it is moved. That would look like:
$("#menu-pages").sortable({
update: function(event, ui) {
$.post("ajax.php", { type: "orderPages", pages: $('#menu-pages').sortable('serialize') } );
$('.row').each(function(i){
$(this).find('div:eq(3)').html(parseInt(i) + 1);
});
}
});
Also not test, and that's assuming cat_sort is 1-indexed and not missing any values etc etc.
I am querying the database to retrieve contents via Jquery Ajax, and by using SetInterval function it queries the database for new contents every 1 min.
My question is How can i keep track of New contents ? For ex: If database has new contents, I want to Add highlight Class to it. How can that be done ?
the Jquery code for Retrieving contents
$(document).ready(hot_listings());
setInterval( "hot_listings();", 10000 );
var ajax_load = "<img class='loading' src='images/indicator.gif' alt='loading...' />";
function hot_listings() {
$.ajax({
url: "hot_listing.php",
cache: false,
success: function(msg) {
$("#hot_properties").html(msg);
}
});
}
Well, i am including the Php too ..
<?php
include("includes/initialize.php");
// hot properties, featured
$per_page = 3;
global $database;
$listings = Listings::hot_listings();
//while ($listing = $database->fetch_array($listings)) {
foreach ($listings as $listing ) {
$listing_id = $listing->listing_id; //initialize listing_id to fetch datas from other table
$photo = Photos::find_by_id($listing_id); //initialize table photo
$comment = Comments::find_by_id($listing_id);
$comment_count = Comments::count_by_id($listing_id);
$photo_count = Photos::count_by_id($listing_id);
//echo $listing['listing_id'];
?>
<li><span class="imageholder">
<img class="listingimageSmall" src="<?php if (!empty($photo->name)) { echo 'uploads/thumbs/'.$photo->name; } else { echo 'images/no-thumb-100.jpg'; } ?>" width="66" height="66" >
</span>
<h3><?php echo ucfirst($listing->title) . ' in ' . ucfirst($listing->city) ; ?></h3>
<p class="description">
<span class="price">Rs <?php echo $listing->price; ?></span>
<span class="media"> <img src="images/icon_img.jpg" alt="Images" width="13" height="12" /> <?php echo $photo_count;?> Images <img src="images/comments.png" alt="Images" width="13" height="12" /> <?php echo $comment_count; ?> comments </span>
</p>
<div class="clear"> </div>
</li>
<?php } // end of foreach
?>
Answer
I recommend that you change your PHP part to emit JSON data about listings.
This can be accomplished through the use of the PHP function json_encode(). You can read more about json_encode() at http://php.net/manual/en/function.json-encode.php.
Then on the client you'll be able to do this:
$.ajax({
url: "hot_listing.php",
cache: false,
success: function(data) {
last_received_listings = data;
build_html_in('#hot_properties', data);
}
});
In an ajax callback you memorize data that you just received and then build HTML markup out of it.
Since you know what listings you already saw, when you get new listings you'll be able to identify new ones.
var new_listings = detect_new_listings(data, last_received_listings);
last_received_listings = data;
build_html_in('#hot_properties');
highlight_listings(new_listings); // set a CSS class on a div or whatever
More details
Possible implementation of detect_new_listings
function detect_new_listings(original, new) {
var result = [];
for(var i = 0; i < original.length; i++) {
var found = false;
// find similar listing in new
for(var j = 0; j < new.length; j++) {
if(original[i].listing_id == new[j].listing_id) {
found = true;
break;
}
}
if(!found) {
result.push(original[i]);
}
}
return result;
}
You could put all listings inside an array in JS and then compare that with the newly fetched list from the PHP file or you could simply check on a date column containing the date for when the row was added and then through PHP; if row is earlier than 1 minute - go ahead and put a class on the HTML element.
I know this is a very basic question, but i couldnt figure how to fix the code even after crawling the web for past 1 hour.
I have an unordered list containing the information about the categories in the database, with cat_id as primary key. and a subject table with cat_id as its foreign key, so i want to access the subjects table through ajax request for given category ID. below is the code i used to generate categories. Where i am stuck is, i dont know which DOM element to fetch in order to send the unique id in the url parameter ..
thanks ..
<ul id="search_form">
<?php
$cat = Category::find_all();
foreach($cat as $category) {
echo '<li id="';
echo $category->cat_id;
echo '"><a href="subject.php?id=';
echo $category->cat_id;
echo'">';
echo $category->category;
echo '</a></li>';
}
?>
</ul>
<div id="results">
<!-- ajax contents goes here -->
</div>
the ajax file is
window.onload = init;
function init() {
if (ajax) {
if (document.getElementById('results')) {
document.getElementById('search_form').onclick = function() {
ajax.open('get', 'subject.php?id='+id ); // subject.php?id=
// how will i pass the variable
ajax.onreadystatechange = function() {
handleResponse(ajax);
}
ajax.send(null);
return false;
}
}
}
}
function handleResponse(ajax) {
if (ajax.readyState == 4) {
if ((ajax.status == 200) || (ajax.status == 304) ) {
var results = document.getElementById('results');
results.innerHTML = ajax.responseText;
results.style.display = 'block';
}
}
}
and the subject.php
<?php
//include("tpl/header.php");
include("includes/initialize.php");
?>
<h2></h2>
<?php
if (isset($_GET['id'])) {
$id= mysql_real_escape_string($_GET['id']);
$subject = Subject::find_subject_for_category($id);
foreach($subject as $subj) {
echo $subj->subject_title;
}
} else {
echo "No ID Provided";
}
?>
I have used Jquery to do these kind of things and it works fine for me.
$.ajax({
type: GET,
url: "subject.php",
data: {id: $('#search_form :selected').val()},
success: function(result){
// callback function
}
});