Updating Values Using Ajax in Yii - ajax

This is my first ever post....
I'm working on a shopping website using Yii-Booster but I'm currently stumped! Basically what I'm trying to achieve is that when a user adds a product to the cart, a modal displays showing an acknowledgement message and then the div with the shopping cart is updated to reflect the new total.
Really simple, innit?? I've spent the entire day trying to get it to work. Any help you can offer would be greatly appreciated.
Oh yeah... one more thing, the dropdown menu in the navbar stops working after almost any sort of AJAX action(loading modals, etc). I'm guessing its caused by a conflict somewhere but I'm completely lost in Jquery/Ajax stuff.
Thanks for the replies. Here's my code:
StoreController:
// action allowing a product to be added to the shopping cart
public function actionAddToCart($id)
{
//fetch item
$item = Item::model()->findByPk($id);
//if item is in cart
if(Yii::app()->shoppingCart->contains($id))
{
//Yii::app()->clientScript->scriptMap['jquery.js'] = true;
//$this->renderPartial('_addToCart',array('data'=>$data),false,true);
echo CJSON::encode(
array(
//'total'=>'Your Cart (N'.number_format(Yii::app()->shoppingCart->getCost()).')',
'addCart'=>$this->renderPartial('_inCart',array('item'=>$item),true),
)
);
//CHtml::ajax();
}
else
{
Yii::app()->shoppingCart->put($item);
//Yii::app()->clientScript->scriptMap['jquery.js'] = true;
//$this->renderPartial('_addToCart',array('data'=>$data),false,true);
//$this->renderPartial('_addToCart',array('item'=>$item),false,true);
echo CJSON::encode(
array(
'total'=>'Your Cart (N'.number_format(Yii::app()->shoppingCart->getCost()).')',
'addCart'=>$this->renderPartial('_addToCart',array('item'=>$item),true),
)
);
}
}
_display (partialview showing the product)
<div style="float: left; display: inline; margin-right: 30px; margin-top: 20px;">
<img style="border: 1px solid black;" src="<?php echo Yii::app()->baseUrl; ?>/images/products/thumbs/<?php echo $data->image; ?>" />
<div style="font-size: 14px; margin-top: 3px;">
Name: <?php echo CHtml::ajaxLink($data->name, array("view", "id"=>$data->id), array('update'=>'#viewdetailsDiv',)); //array(), array('data-toggle'=>'modal','data-target'=>"#".$data->id)); ?><br/>
Category: <?=$data->category->category?><br/>
Gender: <?=$data->gender?><br/>
Price: <?php echo "N".number_format($data->price);?><br/>
<?php //echo CHtml::ajaxLink("Add to Cart", array("addtocart", "id"=>$data->id), array( 'update'=>'#addtocartDiv',)); ?>
<?php echo CHtml::ajaxLink("Add to Cart", array("addtocart", "id"=>$data->id), array( 'type'=>'POST', 'dataType'=>'json',
'success'=>'function(data){
$("#Cart").html(data.total);
}'
)
); ?>
</div>
Here's the code for the view containing the modal
<?php $this->beginWidget('bootstrap.widgets.TbModal', array('id'=>'myModal', 'autoOpen'=>true, 'htmlOptions'=>array('style'=>'margin-top: 2px;'))); ?>
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h4>Your Cart has been updated</h4>
</div>
<div class="modal-body">
<p>The item, <strong><?php echo $item->name; ?></strong> (<?php echo $item->category->category; ?>), has been added to your shopping cart.</p>
</div>
<div class="modal-footer">
<?php $this->widget('bootstrap.widgets.TbButton', array(
'type'=>'primary',
'label'=>'Close',
'url'=>'#',
'htmlOptions'=>array('data-dismiss'=>'modal'),
)); ?>
</div>
<?php $this->endWidget(); ?>

I can't tell you the perfect solution but can give you a suggestion regarding Yii that can solve your problem.
Always load all the jquery or js files used in first request. Never load again any js file in any ajax request, It will a lot of problems.
You can achieve it in simple way
if(Yii::app()->request->isAjaxRequest){
Yii::app()->clientScript->scriptMap['jquery.js'] = true;
}

Related

How do I call the function to check in a view?

How do I check if my database has more than 9 entries, and if it has, I can advance to the next page.
Currently I have this code, but I don't know how to call that in my view:
Here in the controller I have already called the checklogin and see if it has more than 9 entries.
Controller:
function quizzes(){
$this->load->model('Quiz_Model');
$data['categorys'] = $this->Quiz_Model->SearchAllCategorys();
$this->load->view('headerLogged');
$this->load->view('quizzes', $data);
$this->load->view('footer');
}
function proses_quiz($id_category){
$this->load->view('headerLogged');
$checkquiz=$this->Quiz_Model->checkquiz($id_category);
if($checkquiz > 9){
redirect('User_Ctr/quiz/').$id_category;
}else{
$data['error_quiz']="MEH";
$this->load->view('quizzes', $data);
}
$this->load->view('footer');
}
And here it's just the code to make the count:
Model:
public function checkquiz($id_category){
$this->db->select('id_question, COUNT(id_question) as total');
$this->db->from('questions');
$this->db->where('id_category', $id_category);
$result = $this->db->get();
return $result->result();
}
View:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="container">
<h1 class="my-4 text-center text-lg-left">Quizzes</h1>
<div class="row text-center text-lg-left">
<?php foreach($categorys as $cat): ?>
<div class="col-lg-3 col-md-4 col-xs-6" >
<a href="<?php echo 'quiz/'.$cat->id_category ?>" class="d-block mb-4 h-100" >
<img class="img-fluid img-thumbnail" src="<?php echo $cat->img_category ?>" alt="" style="height: 125px; width: 400px">
<?php
if(isset($error_quiz)){
echo $error_quiz;
}
?>
</a>
</div>
<?php endforeach ?>
</div>
</div>
I will answer you question generally.
If you want to call something in the view you have many options like you have the variable already calculated in advance and already passed it to view waiting for a call, or you can click on a link that maybe reload the current view with the new variable done, or you can use ajax to go get the variable from the controller without reloading.
So if the variable has fixed value that doesn't depend on your action, go with the first option or else chose one of the others.

Display comment regarding posts

I am developing a blog using codeigniter, every thing works good like posts are being stored comments are being made likes also works the only problem is fetching the comments using codeigniter against each post. What i want to do is that i want to send id to controller of each id when page loads. Here is the screenshot to make it more clear how i am working.
Front end is like this
Now the code section:
1. Code on the blog page where all messages and posts are being shown
<div class="col-lg-11 col-md-10 col-sm-10 col-xs-9 post_message" id="getComments<?php echo $blog -> blog_id; ?>">
<p>
<?php echo $blog -> message; ?>
</p>
<span class="pull-left">
<small> Posted By: <?php echo $blog -> name; ?></small>
</span>
<!-- onclick="get_comments(this.id, '<?php //echo base_url('users/get_comments_total'); ?>')" id="<?php// echo $blog -> blog_id; ?>-->
<a>
<i class='fa fa-comment' aria-hidden='true'></i> Comments (<small> <?php echo $rows; ?> </small>)
</a>
<a onclick="update_like('<?php echo $blog -> blog_id; ?>', '<?php echo base_url('users/update_like'); ?>')">
<i class='fa fa-thumbs-up' aria-hidden='true'></i> Likes (<small><?php echo $blog -> likes; ?></small>)
</a>
<div class="result_id<?php echo $blog -> blog_id; ?>" style="display: block;float: left;width: 100%;"></div>
</div> <!-- End of post message -->
In the above code there is a line written in comments where on-click function is defined i want to pass each id on page load to controller instead of click and all this code is written in foreach loop.
Help me with this thing or tell if there is any better idea to achieve this. Please do see the image attached with this so that you can know easily how i want to display the comments. one hint is like FB comments.
What is $rows?
If the likes are working OK then you can use the same idea for the comments. Probably you have joined the likes table and that is why you have $blog -> likes;. You should join the comments table to the query and then use Comments (<small> <?php echo $blog->comments; ?> </small>).
If this does not work you should provide your query in the model and your database structure.

How Can I check if Page is single page of Custom Post Type in Wordpress

On the Homepage I have called the content of Custpm Post Type with Ajax with this code
jQuery(document).ready(function($){
$.ajaxSetup({cache:false});
$(".sector_item a").click(function(){
var post_link = $(this).attr("href");
$(".sector_item_content").html("<div class='load' style='position:relative;margin-top:50px;padding-bottom:50px;'><img src='<?php bloginfo("template_url"); ?>/images/ajax-loader.gif'></div>");
$(".sector_item_content").load(post_link);
return false;
});
});
But In the single Page of this same Post Type I need to have another design with content so how I can detect the single page. I tried with Wordpess is_single() function but it doesnt work it displayed anyway in ajax.How Can I fix this?
Here is my single template.php
<?php if(is_singular('sector' )){
echo 'Single page' ;
}else{
while (have_posts() ) : the_post(); ?>
<div class="container single_page_inner">
<div class="row clearfix">
<div class="col-md-10 column" style="float:none;margin:auto;">
<div class="sector_single_title">
<?php the_title();?>
</div>
<div class="single_sector_contentmain"> <?php the_content();?></div>
<div class="single_sector_more">
<img src="<?php bloginfo(template_url);?>/images/single_secormoreline.png"/>
<div class="single_sector_button">
<span class="single_sec_leftline"></span>
<span class="single_sec_rightline"></span>
Click Here To Read More
<div class="more_line"></div>
</div>
</div>
</div>
</div>
</div>
<?php endwhile; ?>
If you want to be able to do different things when your single.php files is loaded from Ajax, you need to tell it somehow when it is getting an Ajax request.
One approach would be to add a parameter to your call, like this:
var post_link = $(this).attr("href") + '?isajax=1';
Then in your single.php file, test for this parameter:
<?php if(!empty($_GET['isajax'])){
// This is Ajax - display in Ajax format
} else {
// This is not Ajax - display in standard single.php format
}
use this:
is_singular('YOUR_POST_TYPE' );
CODEX

Magento - Four Products on Homepage - Random Order - Foreach Loop

I'm trying to get 4 random products on the homepage using PHP within a TPL file I've created. I'd like to be able to format the products in a foreach loop as I'm using some formatting in the code seen below...
<div class="three columns">
<div class="product_container no_border">
<div class="product">
<img src="<?php echo $this->getSkinUrl('images/products/place_holder.jpg'); ?>" alt=" ">
</div>
<div class="product_title">
240 Serving Package
</div>
<div class="price_hp">$454.99</div>
<div class="free_shipping">
<div class="fs"></div>
Free shipping for this package
</div>
<div class="shop_btn">
ADD TO CART
</div>
</div>
</div>
I don't know what PHP to use though to grab the 4 products from any category and randomize the order. May I have some guidance please?
Thanks!
use following code in your phtml file for randomize products..
$categoryid = 15;
$category = new Mage_Catalog_Model_Category();
$category->load($categoryid);
$products = $category->getProductCollection();
$products->addAttributeToSelect('*');
$products->getSelect()->order('RAND()');
$products->getSelect()->limit(4);
foreach($products as $prod)
{
echo $prod->getName() ."<br>";
$img=$prod->getSmallImageUrl();
echo "<img src='$img'>" ."<br>";
}

Joomla 1.5. How to add Like / Dislike button on videos / images?

I'm useing Joomla 1.5 AllVideoShare (Version 1.2.4) extension.
QUESTION PART 1
I want to ask you how to make like button on videos thumbs/images? For example if user likes video clip or image he can click like button and It counts how many users like It. It can be simple like button or facebook button if possible. Also maybe possible to make Like / Dislike buttons (If user don't like this video/image he can dislike It)
Example where I want to place:
http://img689.imageshack.us/img689/268/likecp.png
This is my part of code where videos are publishing:
<?php if ($this->params->get('show_'.$header, 1)) : ?>
<h2> <?php echo $this->escape($this->params->get($header)); ?> </h2>
<?php endif; ?>
<div id="avs_gallery2<?php echo $this->escape($this->params->get('pageclass_sfx')); ?>">
<?php
if(!count($videos)) echo JText::_('ITEM_NOT_FOUND');
for ($i=0, $n=count($videos); $i < $n; $i++) {
$clear = '';
if($column >= $this->cols) {
$clear = '<div style="clear:both;"></div>';
$column = 0;
$row++;
}
$column++;
echo $clear;
?>
<span class="name"><?php echo $categories[$i]->name; ?></span>
<div id="testas" class="avs_thumb" style="width:190px;" onclick='javascript:location.href="<?php echo JRoute::_($link.$videos[$i]->slug.$qs); ?>"'>
<img class="arrow" src="<?php echo JURI::root(); ?>components/com_allvideoshare/assets/play.gif" border="0" style="margin-left:80px; margin-top:47px;" />
<img class="image" src="<?php echo $videos[$i]->thumb; ?>" width="190; " height="120;" title="<?php echo JText::_('CLICK_TO_VIEW') . ' : ' . $videos[$i]->title; ?>" border="0" />
<span class="title"><FONT COLOR="#000000"><?php echo $videos[$i]->title; ?></font></span>
<span class="views"><FONT COLOR="#000000"><?php echo JText::_('Peržiūros'); ?> : <strong><?php echo $videos[$i]->views*2+1; ?></strong></font></span>
<div class="avs_category_label"><?php echo JText::_('Kategorija'); ?> : <strong><?php echo $videos[$i]->category; ?></strong></div>
</div>
<?php } ?>
QUESTION PART 2
After I add Like / Dislike buttons will be possible to sort them by "Most popular" (Which video have most likes) or there are so hard work?
Example: http://www.anekdotai.lt/
QUESTION PART 3
In the same place as Like / Dislike button I want to put Facebook share button. I have script which works, but I can't succesfully add It to this place.
FB Share script:
<?php
defined('_JEXEC') or die('Restricted access');
$linkTxt = $params->get( 'linkTxt', '' );
$linkColor = $params->get( 'linkColor', '' );
$linkHColor = $params->get( 'linkHColor', '' );
$theUrl = $params->get( 'theUrl', '1' );
$wholeUrl = "location.href.substring(0,location.href.lastIndexOf('/'))";
$currentUrl = "location.href";
?>
<script>function fbs_click() {u=<?php if($params->get('theUrl', 1))
{
echo $currentUrl;
}
else{
echo $wholeUrl;
} ?>;t=document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}</script><style> html .fb_share_button { display: -moz-inline-block; display:inline-block; padding:1px 1px 1px 20px; height:17px; color:#<?php echo $linkColor ?>; background:url(http://static.ak.facebook.com/images/share/facebook_share_icon.gif?6:26981) no-repeat left; } html .fb_share_button:hover { color:#<?php echo $linkHColor ?>; background:url(http://static.ak.facebook.com/images/share/facebook_share_icon.gif?6:26981) no-repeat left; text-decoration:none; } </style> <a rel="nofollow" href="http://www.facebook.com/share.php?u=<url>" class="fb_share_button" onclick="return fbs_click()" target="_blank" style="text-decoration:none;"><?php echo $linkTxt; ?></a>
If I put It to Video publishing code I get error:
Fatal error: Call to a member function get() on a non-object in ..../juokoera.lt/public_html/components/com_allvideoshare/views/videos/tmpl/default.php on line 26
Thank you for answers.
Try adding the following code which will define the $params variable:
$params = JComponentHelper::getParams( 'com_yourcomponent' );

Resources