I´d like to use foreach to echo all images-path, but when a variable is empty $bild_5 than shouldn't display any HTML code around.
My code:
<html>
<?php
// var
$url = "http://www.URL/assets/";
$bild_1 = $url . "bild-1.jpg";
$bild_2 = $url . "bild-2.jpg";
$bild_3 = $url . "bild-3.jpg";
$bild_4 = $url . "bild-4.jpg";
$bild_5 = "";
// array
$bilder = array ("$bild_1", "$bild_2", "$bild_3", "$bild_4", "$bild_5");
?>
<ul>
<!-- foreach / Template -->
<?php foreach($bilder as $bild) { ?>
<li><img src="<?php echo $bild; ?>"</li>
<?php } ?>
</ul>
</html>
HTML-OUTPUT
<html>
<ul>
<li><img src="http://www.URL/assets/bild-1.jpg"</li>
<li><img src="http://www.URL/assets/bild-2.jpg"</li>
<li><img src="http://www.URL/assets/bild-2.jpg"</li>
<li><img src="http://www.URL/assets/bild-4.jpg"</li>
<li><img src=""</li> // Don´t display this HTML code; ( $bild_5 = ""; )
</ul>
</html>
Thanks for your help
Ogni
You can use continue to skip
<?php foreach($bilder as $bild) { ?>
<?php if (empty($bild)) continue; ?>
<li><img src="<?php echo $bild; ?>"</li>
<?php } ?>
I would also recommend that you use the alternate syntax for control structures when you mix PHP and HTML. It's easier to read
<?php foreach($bilder as $bild) : ?>
<li><img src="<?php echo $bild; ?>"</li>
<?php endforeach; ?>
Reference - http://php.net/manual/en/control-structures.alternative-syntax.php
Either use continue; as stated above, or simply let array_filter($bilder); run before your foreach
Related
I'm working on adding this to the com_content blog.php override.
Where we have the intro_items I need to have it count through 3 articles and then add a div where I can drop an ad script and than have it carry on and load the remaining 7 articles.
This is the intro_items loop. In parameters I have it set to 10 articles
<?php
$introcount = count($this->intro_items);
$counter = 0;
?>
<?php if (!empty($this->intro_items)) : ?>
<?php foreach ($this->intro_items as $key => &$item) : ?>
<?php $rowcount = ((int) $key % (int) $this->columns) + 1; ?>
<?php if ($rowcount === 1) : ?>
<?php $row = $counter / $this->columns; ?>
<div class="items-row cols-<?php echo (int) $this->columns; ?> <?php echo 'row-' . $row; ?> row-fluid clearfix">
<?php endif; ?>
<div class="span<?php echo round(12 / $this->columns); ?>">
<div class="item column-<?php echo $rowcount; ?><?php echo $item->state == 0 ? ' system-unpublished' : null; ?>"
itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
<?php
$this->item = &$item;
echo $this->loadTemplate('item');
?>
</div>
<!-- end item -->
<?php $counter++; ?>
</div><!-- end span -->
<?php if (($rowcount == $this->columns) or ($counter == $introcount)) : ?>
</div><!-- end row -->
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
I came up with the following, which works, but would like an opinion if there is a better way to do this.
<?php
$introcount = count($this->intro_items);
$counter = 0;
?>
<?php if (!empty($this->intro_items)) : ?>
<?php foreach ($this->intro_items as $key => &$item) : ?>
<?php $rowcount = ((int) $key % (int) $this->columns) + 1; ?>
<?php if ($rowcount === 1) : ?>
<?php $row = $counter / $this->columns; ?>
<div class="items-row cols-<?php echo (int) $this->columns; ?> <?php echo 'row-' . $row; ?> row-fluid clearfix">
<?php endif; ?>
<?php if ($row != 2) : ?>
<div class="span<?php echo round(12 / $this->columns); ?>">
<div class="item column-<?php echo $rowcount; ?><?php echo $item->state == 0 ? ' system-unpublished' : null; ?>"
itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
<?php
$this->item = &$item;
echo $this->loadTemplate('item');
?>
</div>
<?php endif; ?>
<?php if ($row === 2) : ?>
<div class="span<?php echo round(12 / $this->columns); ?>">
<div class="item column-<?php echo $rowcount; ?><?php echo $item->state == 0 ? ' system-unpublished' : null; ?>"
itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
<?php
$this->item = &$item;
echo $this->loadTemplate('item');
?>
<!-- mobile ad banner zone -->
<div class="cat-banner bannerzonepadding visible-phone">
<script type="text/javascript" language="javascript" src="http://myadsrc.demo"></script>
</div>
</div>
<?php endif; ?>
<!-- end item -->
<?php $counter++; ?>
</div><!-- end span -->
<?php if (($rowcount == $this->columns) or ($counter == $introcount)) : ?>
</div><!-- end row -->
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
Would this approach work?
you add an ID to a wrapper around your list of intro_items
use jQuery and CSS nth-child selector to target the third child in the intro_items list
then use jQuery .after() function to insert the HTML for your ad
Pseudo code
$("#intro_items_wrapper .items-row:nth-child(3)").after('<!-- mobile ad code here -->');
Actual code
$("#intro_items_wrapper .items-row:nth-child(3)").after('<!-- mobile ad banner zone -->
<div class="cat-banner bannerzonepadding visible-phone">
<script type="text/javascript" language="javascript" src="http://myadsrc.demo"></script>
</div>');
Here's a working demo:
https://codepen.io/panchroma/pen/EEwaQX
Good luck!
This is Cakephp 3.5, So I have three businesses 1, 2, 3. I have a view to show Estimated Revenue From Fees.
On the index page I have a three column Div
<div class="row">
<div class="col-md-12">
<h2><?= __('Estimated Revenue From Fees') ?></h2>
<div class="row">
<div class="column">
<h4>Business One</h4>
<ul>
<?php foreach ($estimatedRevenueFromCFeesBiz1 as $estimatedRevenueFromFeeBiz1): ?>
<li class="actions">
<?= $this->Html->link(__( h($estimatedRevenueFromFeeBiz1->year), ['action' => 'view', $estimatedRevenueFromFeeBiz1->id]) ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="column">
<h4>Business Two</h4>
<?php foreach ($estimatedRevenueFromFeesNauBiz2 as $estimatedRevenueFromFeeBiz2): ?>
<li class="actions">
<?= $this->Html->link(__( h($estimatedRevenueFromFeeNauBiz2->year), ['action' => 'view', $estimatedRevenueFromFeeBiz2->id]) ?>
</li>
<?php endforeach; ?>
</div>
<div class="column">
<h4>Business Three</h4>
<?php foreach ($estimatedRevenueFromCourseFeesUa as $estimatedRevenueFromCourseFeeUa): ?>
<li class="actions">
<?= $this->Html->link(__( h($estimatedRevenueFromFeeBiz3->year), ['action' => 'view', $estimatedRevenueFromFeeBiz3->id]) ?>
</li>
<?php endforeach; ?>
</div>
</div>
</div>
</div>
In my controller I've set up like this:
public function index()
{
$estimatedRevenueFromFeesBiz1 = $this->EstimatedRevenueFromFeesBiz1->find('list', array( 'conditions' => 'business_id' == 1));
$estimatedRevenueFromFeesBiz2 = $this->EstimatedRevenueFromFeesBiz2->find('list', array( 'conditions' => 'business_id' == 2));
$estimatedRevenueFeesBiz3 = $this->EstimatedRevenueFromFeesBiz3->find('list', array( 'conditions' => 'business_id' == 1));
$this->set(compact('estimatedRevenueFromFeesBiz1', 'estimatedRevenueFromFeesBiz2', 'estimatedRevenueFromFeesBiz3'));
}
I'm getting a Call to a member function find() on boolean
Error in: ROOT\src\Controller\EstimatedRevenueFromCourseFeesController.php, line 26 which is the
$estimatedRevenueFromFeesBiz1 = $this->EstimatedRevenueFromFeesBiz1->find('list', array( 'conditions' => 'business_id' == 1)); line.
I figured it out. I changed the controller back to just calling the whole table:
public function index()
{
$this->paginate = [
'contain' => ['Businesses']
];
$estimatedRevenueFromFees = $this->paginate($this->EstimatedRevenueFromFees);
$this->set(compact('estimatedRevenueFromFees'));
}
I then added a condition into the index.ctp file:
<h4>Business One</h4>
<ul>
<?php foreach ($estimatedRevenueFromFees as $estimatedRevenueFromFee): ?>
<?php if ($estimatedRevenueFromFee['business_id'] == 1): ?>
<li class="actions">
<?= $this->Html->link(__( h($estimatedRevenueFromFee->year), ['action' => 'view', $estimatedRevenueFromFee->id]) ?>
</li>
<?php else: ?>
<?php continue; ?>
<?php endif; ?>
<?php endforeach; ?>
</ul>
Well, based on what you said and on your own answer, it looks like what you were trying to do was this:
public function index() {
$estimatedRevenueFromFeesBiz1 = $this->EstimatedRevenueFromFees->find('list', ['conditions' => ['business_id' == 1]]);
$estimatedRevenueFromFeesBiz2 = $this->EstimatedRevenueFromFees->find('list', ['conditions' => ['business_id' == 2]]);
$estimatedRevenueFeesBiz3 = $this->EstimatedRevenueFromFees->find('list', ['conditions' => ['business_id' == 1]]);
$this->set(compact('estimatedRevenueFromFeesBiz1', 'estimatedRevenueFromFeesBiz2', 'estimatedRevenueFromFeesBiz3'));
}
What changes is your condition (business_id). But you are always querying over the same table (EstimatedRevenueFromFees).
Bare in mind that in your solution you are paginating. So you might end up having every record in a page with a certain business_id, or whatever combination.
Need some help getting widget to sort the reviews from low to high. I know this is reverse of the norm, but this website focuses on how "bad" something is. The website is here: http://designtatics.fatcow.com/Badkickstarter/ it's the second tab down called top 3. Excuse the mess, still a work in progress.
// order by rating?
if (isset($order) && $order == 'rating') {
$query_args['orderby'] = 'meta_value';
}
else {
$query_args['orderby'] = 'date';
}
$r = new WP_Query($query_args);
I've already tried adding $query_args['order'] = 'ASC'; with no luck. This is all new to me so the more specific the better. Thanks!
UPDATE: I think I was trying to modify the wrong widget, heres the new code:
<?php
class Bunyad_TabbedRecent_Widget extends WP_Widget
{
public function __construct()
{
parent::__construct(
'bunyad-tabbed-recent-widget',
'Bunyad - Recent Tabs',
array('description' => __('Tabs: Recent, category1, category2...', 'bunyad-widgets'), 'classname' => 'tabbed')
);
add_action('save_post', array($this, 'flush_widget_cache'));
add_action('deleted_post', array($this, 'flush_widget_cache'));
add_action('switch_theme', array($this, 'flush_widget_cache'));
// init hook
add_action('init', array($this, 'init'));
}
public function init()
{
// only in admin cp for form
if (is_admin()) {
wp_enqueue_script('widget-tabs', plugins_url('/bunyad-widgets/js/widget-tabs.js'));
}
}
// #todo wrap existing widgets with in-memory cache
public function widget($args, $instance)
{
global $post; // setup_postdata not enough
// set defaults
$titles = $cats = $tax_tags = array();
extract($args);
extract($instance);
// missing data?
if (!count($titles) OR !count($cats)) {
_e('Recent tabs widget still need to be configured! Add tabs, add a title, and select type for each tab in widgets area.', 'bunyad-widgets');
return;
}
$tabs = array();
foreach ($titles as $key => $title) {
// defaults missing?
if (empty($tax_tags[$key])) {
$tax_tags[$key] = '';
}
if (empty($cats[$key])) {
$cats[$key] = '';
}
$tabs[$title] = array('cat_type' => $cats[$key], 'tag' => $tax_tags[$key]);
}
// latest posts
$posts = $this->get_posts($tabs, $number);
?>
<?php echo $before_widget; ?>
<ul class="tabs-list">
<?php
$count = 0;
foreach ($posts as $key => $val): $count++; $active = ($count == 1 ? 'active' : '');
?>
<li class="<?php echo $active;?>">
<?php echo $key; ?>
</li>
<?php endforeach; ?>
</ul>
<div class="tabs-data">
<?php
$i = 0;
foreach ($posts as $tab => $tab_posts): $i++; $active = ($i == 1 ? 'active' : ''); ?>
<ul class="tab-posts <?php echo $active; ?> posts-list" id="recent-tab-<?php echo esc_attr($i); ?>">
<?php if ($tabs[$tab] == 'comments'): ?>
<?php
foreach ($tab_posts as $comment):
?>
<li class="comment">
<span class="author"><?php printf('%s said', get_comment_author_link($comment->comment_ID)); ?></span>
<p class="text"><?php comment_excerpt($comment->comment_ID); ?></p>
<?php echo get_the_title($comment->comment_post_ID); ?>
</li>
<?php
endforeach;
?>
<?php else: ?>
<?php foreach ($tab_posts as $post): setup_postdata($post); ?>
<li>
<a href="<?php the_permalink() ?>"><?php the_post_thumbnail('post-thumbnail', array('title' => strip_tags(get_the_title()))); ?>
<?php if (class_exists('Bunyad') && Bunyad::options()->review_show_widgets): ?>
<?php echo apply_filters('bunyad_review_main_snippet', ''); ?>
<?php endif; ?>
</a>
<div class="content">
<time datetime="<?php echo get_the_date('Y-m-d\TH:i:sP'); ?>"><?php echo get_the_date(); ?> </time>
<span class="comments"><a href="<?php echo esc_attr(get_comments_link()); ?>"><i class="fa fa-comments-o"></i>
<?php echo get_comments_number(); ?></a></span>
<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr(get_the_title() ? get_the_title() : get_the_ID()); ?>">
<?php if (get_the_title()) the_title(); else the_ID(); ?></a>
</div>
</li>
<?php endforeach; ?>
<?php endif; ?>
</ul>
<?php endforeach; ?>
</div>
<?php echo $after_widget; ?>
<?php
wp_reset_postdata();
}
public function get_posts($tabs, $number)
{
// posts available in cache? - use instance id to suffix
$cache = get_transient('bunyad_tabbed_recent_posts');
if (is_array($cache) && isset($cache[$this->number])) {
return $cache[$this->number];
}
// get posts
$args = array('numberposts' => $number, 'ignore_sticky_posts' => 1);
foreach ($tabs as $key => $val) {
$opts = array();
switch ($val['cat_type']) {
case 'popular':
$opts['orderby'] = 'comment_count';
break;
case 'comments':
$posts[$key] = get_comments(array('number'=> $number, 'status' => 'approve'));
continue 2; // jump switch and foreach loop
case 'top-reviews':
// get top rated of all time
$opts = array_merge($opts, array('orderby' => 'meta_value', 'meta_key' => '_bunyad_review_overall'));
break;
case 'recent':
break;
case 'tag':
$opts['tag'] = $val['tag'];
break;
default:
$opts['cat'] = intval($val['cat_type']);
break;
}
//$query = new WP_Query(array_merge($args, $opts));
$posts[$key] = get_posts(array_merge($args, $opts));
}
if (!is_array($cache)) {
$cache = array();
}
$cache[ $this->number ] = $posts;
set_transient('bunyad_tabbed_recent_posts', $cache, 60*60*24*30); // 30 days transient cache
return $posts;
}
public function flush_widget_cache()
{
delete_transient('bunyad_tabbed_recent_posts');
}
public function update($new, $old)
{
// fix categories
foreach ($new['cats'] as $key => $cat) {
$new['cats'][$key] = strip_tags($cat);
}
foreach ($new['titles'] as $key => $title) {
$new['titles'][$key] = strip_tags($title);
}
foreach ($new['tax_tags'] as $key => $tag) {
$new['tax_tags'][$key] = trim(strip_tags($tag));
}
$new['number'] = intval($new['number']);
// delete cache
$this->flush_widget_cache();
return $new;
}
public function form($instance)
{
$instance = array_merge(array('titles' => array(), 'cats' => array(0), 'number' => 4, 'cat' => 0, 'tax_tags' => array()), $instance);
extract($instance);
?>
<style>
.widget-content p.separator { padding-top: 10px; border-top: 1px solid #d8d8d8; }
.widget-content .tax_tag { display: none; }
</style>
<div id="tab-options">
<script type="text/html" class="template-tab-options">
<p class="title separator">
<label><?php printf(__('Tab #%s Title:', 'bunyad-widgets'), '<span>%n%</span>'); ?></label>
<input class="widefat" name="<?php
echo esc_attr($this->get_field_name('titles')); ?>[%n%]" type="text" value="%title%" />
</p>
<div class="cat">
<label><?php printf(__('Tab #%s Category:', 'bunyad-widgets'), '<span>%n%</span>'); ?></label>
<?php
$r = array('orderby' => 'name', 'hierarchical' => 1, 'selected' => $cat, 'show_count' => 0);
// categories list
$cats_list = walk_category_dropdown_tree(get_terms('category', $r), 0, $r);
// custom options
$options = array(
'recent' => __('Recent Posts', 'bunyad-widgets'),
'popular' => __('Popular Posts', 'bunyad-widgets'),
'top-reviews' => __('Top Reviews', 'bunyad-widgets'),
'tag' => __('Use a Tag', 'bunyad-widgets'),
);
?>
<select name="<?php echo $this->get_field_name('cats') .'[%n%]'; ?>">
<?php foreach ($options as $key => $val): ?>
<option value="<?php echo esc_attr($key); ?>"<?php echo ($cat == $key ? ' selected' : ''); ?>><?php echo esc_html($val); ?></option>
<?php endforeach; ?>
<optgroup label="<?php _e('Category', 'bunyad-widgets'); ?>">
<?php echo $cats_list; ?>
</optgroup>
</select>
<div class="tax_tag">
<p><label><?php printf(__('Tab #%s Tag:', 'bunyad-widgets'), '<span>%n%</span>'); ?></label> <input type="text" name="<?php
echo esc_attr($this->get_field_name('tax_tags')); ?>[%n%]" value="%tax_tag%" /></p>
</div>
<p>[x] <?php _e('remove', 'bunyad-widgets'); ?></p>
</div>
</script>
<p class="separator"><?php _e('Add More Tabs', 'bunyad-widgets'); ?></p>
<?php
if (is_integer($this->number)): // create for valid instances only
foreach ($cats as $n => $cat):
?>
<script>
jQuery(function($) {
$('.widget-liquid-right [id$="bunyad-tabbed-recent-widget-'+ <?php echo $this->number; ?> +'"] #add-more-tabs').trigger(
'click',
[{
'n': <?php echo ($n+1); ?>,
'title': '<?php echo esc_attr($titles[$n]); ?>',
'selected': '<?php echo esc_attr($cat); ?>',
'tax_tag': '<?php echo esc_attr($tax_tags[$n]); ?>'
}]);
});
</script>
<?php
endforeach;
endif;
?>
</div>
<p><label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('Number of posts in each tab:', 'bunyad-widgets'); ?></label>
<input id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo $number; ?>" size="3" />
</p>
<?php
}
}
this is script of "tabs"module I want to change to select box with options
I tried to change the code but I could not this original code:
can someone help me?
<script type="text/javascript">
window.addEvent('load',function(){
var spTab<?php echo $uniqid ?> = new sptabs($('sptab<?php echo $uniqid ?>'), {
animation : <?php echo "'" . $animation . "'" ?>,
btnPos: <?php echo "'" . $btnPos . "'" ?>,
activator: <?php echo "'" . $activator . "'" ?>,
transition: <?php echo 'Fx.Transitions.' . $transition ?>,
fxduration: <?php echo $fxspeed ?>,
autoHeight : <?php echo $body_height ?>,
fixedHeight: <?php echo $fixed_height ?>
});
});
</script>
<div class="<?php echo $color ?>" id="sptab<?php echo $uniqid ?>">
<?php foreach ($list as $item) : ?>
<div style="display:none">
<div class="tab-padding">
<h2 style="display:none" class="title"><span id="<?php echo (preg_replace('/\s+/', '_',strtolower($item['title']))); ?>" class="sptab-title<?php echo ($item['sfx']) ? ' sptab_sfx' . $item['sfx'] : ''; ?>"><?php echo $item['title']; ?></span></h2>
<?php echo $item['content']; ?>
<div style="clear:both"></div>
</div>
</div>
<?php endforeach; ?>
</div>
I think you're looking for something like this:
<select>
<?php foreach ($list as $item) : ?>
<option><?php echo $item['title']; ?></option>
<?php endforeach; ?>
</select>
Note that you won't need the javascript you provided in your question
First all, I am still learning CakePHP and I am close to ZERO using JQuery.
I would like to get help for the following problem I am having:
I have an Articles_Controller a Comments_Controller and Users_Controller
Currently my articles_controller display an article and its comments are loaded on that page
Whoever user inputted the comment will also appear along with his/her image
On each comment I have added a like/dislike button.
Example:
Right now, however, I am only able to display it. What I wanted to accomplish is to use JQuery so that when a user clicks on the Thumbs Up or Thumbs Down image the like and disliked fields are automatically updated in the Db. Also, using JQuery I would like to update those same values in the View. Please my code below and thank you for your help.
articles/view.ctp
<div id="articles_comments">
<p>
Comments
</p>
<?php
foreach($comments as $comment){
?>
<div id="articles_comments_user">
<img src="<?php echo $comment['User']['image']; ?>">
<p>
<?php
$created = $comment['Comment']['created'];
echo $comment['User']['first_name'];
echo " ";
echo $comment['User']['last_name'];
echo " ";
//echo $comment['Comment']['created'];
echo $this->Time->timeAgoInWords(
$comment['Comment']['created'],
array(
'end'=>'+150 years'
)
);
?>
<p>
</div>
<div id="articles_comments_comment">
<table>
<tr>
<td style="width:85%">
<?php echo $comment['Comment']['comment'];?>
</td>
<td style="width:15%;border-left:solid thin teal;">
<div style="float:left;">
<?php echo $comment['Comment']['liked'];?>
<img width="20" src="/img/icons/thumb-up-icon.png"
</div>
<div style="float:right;margin-left:10px;">
<?php echo $comment['Comment']['disliked'];?>
<img width="20" src="/img/icons/thumb-down-icon.png">
</div>
</td>
</tr>
</table>
</div>
<?php
}
?>
<div class="articles_add_comment" id="formUpdateID">
<hr style="width:100%"><br>
<div style="float:left">
<h3>Seu Commentario:</h3>
<?php
echo $form->create(
'Comment',
array(
'url'=>array(
'controller'=>'articles',
'action'=>'view',
$article['Article']['id']
),
'class' => 'articles_form',
'id' => 'loginForm'
)
);
echo $form->input(
'Comment.comment',
array(
'label' => false,
'type' => 'textarea',
'div' => 'articles_comments_textarea',
'cols' => 90,
'rows' => 3
)
);
?>
</div>
<div style="float:right">
<?php
echo $this->Form->submit(
'Send',
array(
'class' => 'articles_comments_button'
)
);
echo $form->end();
?>
</div>
<div class="ajax-save-message">
<?php echo $this->Session->flash(); ?>
</div>
</div>
</div>
Comments is generated from the Articles View action
I was able to fix my problem by the following upon some research and try outs:
View file
<?php foreach $commments as $commment{ ?>
// .............................................................................
<td style="vertical-align:middle;border-left:solid thin teal;padding-left:5px;">
<div class="voteup" style="margin-left:10px;float:left;width:55px;">
<p style="display:none;float:left">
<?php echo $comment['Comment']['id']; ?>
</p>
<div style="float:left" id="article_thumbsUp">
<?php echo $comment['Comment']'liked'];?>
</div>
<img width="20" src="/img/icons/thumb-up-icon.png">
</div>
<div class="votedown" style="float:left;width:55px;">
<p style="display:none;float:left">
<?php echo $comment['Comment']['id']; ?>
</p>
<div style="float:left" id="article_thumbsDown">
<?php echo $comment['Comment']'disliked'];?>
</div>
<img width="20" src="/img/icons/thumb-down-icon.png">
</div>
</td>
// ...............................................................................
<?php } ?>
jQuery I used
<script>
$(document).ready(function(){
$(".voteup").click(function() {
var Id = $(this).children("p").text();
$(this).children("#article_thumbsUp").load("/comments/voteup/"+Id);
});
});
</script>
<script>
$(document).ready(function(){
$(".votedown").click(function() {
var Id = $(this).children("p").text();
$(this).children("#article_thumbsDown").load("/comments/votedown/"+Id);
});
});
</script>
And both of my actions in my comments_controller.php
function voteUp($id = null){
$this->autoRender = false;
if($this->RequestHandler->isAjax()){
$this->Comment->id = $id;
if($this->Comment->saveField('liked',$this->Comment->field('liked')+1)){
}
}
$newValue = $this->Comment->findById($id);
return $newValue['Comment']['liked'];
}
function voteDown($id = null){
$this->autoRender = false;
if($this->RequestHandler->isAjax()){
$this->Comment->id = $id;
if($this->Comment->saveField('disliked',$this->Comment->field('disliked')+1)){
}
}
$newValue = $this->Comment->findById($id);
return $newValue['Comment']['disliked'];
}
This is my entire code in detail and hopefully it can help someone else. This is the way I know how to do, and if you have any better way, I was be glad to know. Thanks a lot. THIS WORKS GREAT. I JUST NEED TO ADD A FEW MORE THINGS TO THIS SYSTEM, SUCH AS ONLY ALLOW REGISTERED USERS TO VOTE AND ONLY ONCE PER COMMENT. THAT WILL INVOLVE CREATING ANOTHER TABLE TO TRACK THAT.
Personally, I would create actions in the Comments_Controller, voteup and votedown. Then, make the thumbs up and thumbs down images link to /comments/voteup/id, etc.
After doing this, use jQuery to prevent a page reload when they're clicked, as such...
<a class="voteup" href="<?php echo $this->base;?>/comments/voteup/<?php echo $comment['Comment']['id'];?>">
<img ... />
</a>
<script>
$(".voteup").click(function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('href),
success: function() {
// Update vote counter
}
});
});
</script>
I'm sure you can piece together the rest.