Call Render Partial using time interval in YII - php

I want to update a div contents automatically with refresh whole page. So i did Ajax renderPartial in YII. Now I implement using AJAX button onclick
My code as follows
<?php
echo CHtml::ajaxButton ("Update data",
CController::createUrl("blog/UpdateAjax?url=$url"),
array('update' => '#inrscrn'));
?>
Now I want to render with in a time limit please help

Your question is not very clear. I suppose you want to setup an automatical & periodical refresh of the content within a div instead of clicking on the button.
This is the JavaScript you need on your page:
<script type="text/javascript">
timeout = 60 * 1000; // in Milliseconds -> multiply with 1000 to use seconds
function refresh() {
<?php
echo CHtml::ajax(array(
'url'=> CController::createUrl("blog/UpdateAjax?url=".$url),
'type'=>'post',
'update'=> '#inrscrn',
))
?>
}
window.setInterval("refresh()", timeout);
</script>
But it is not a good approach to send an URL to your controler, rather make a direct request to to make a special AJAX return of a controler which needs to return the correspondent data.
<?php
public function actionTest(){
if (isset($_REQUEST['AJAX']) || Yii::app()->getRequest()->getIsAjaxRequest()) {
$this->renderPartial(
'test',
array('model' => $model),
false,
true
);
} else {
$this->render(
'test',
array('model' => $model),
);
}
}
?>

Related

PHP calling function with parameters by clicking on HTML div

I am trying to make a delete button which I'll be able to delete some user from my database but main thing how to call PHP function with clicking on some div etc..
<div class="cross" onclick='<?php deleteUser("Nickname")?>'>X</div>
<?php
function deleteUser($username) {
//... code
}
?>
Html can't directly call php, it can do a separate call to load the same page, with the action.
<?php
function deleteUser($username){}
if($_GET['action'] == "delete")
{
deleteUser($_GET['username']);
}
?>
<a class="cross" href='?action=delete&username=NickName'>X</a>
The reason for this is because PHP runs on the server, BEFORE anything is sent to the browser. So it requires another page load to run the function by clicking something. It is possible to use javascript and AJAX calls to send a call to a php script without reloading the main page. Just look into Jquery's post or ajax features.
You cannot call a PHP function that resides on the server by just clicking on a div that exists on the client browser.
You need to trigger a Javascript event (using e.g. jQuery), that will call a function on the server (e.g. through AJAX), that after checking the parameters are correct and the user has the right of calling it will do what you seek.
There are ready-made frameworks that would allow you to do that.
Otherwise (after including jQuery in your HTML page) you can do something like,
<div class="cross" id="deleteUserButton" data-user="nickname">X</div>
<script type="text/javascript">
$('#deleteUserButton').on('click', function() {
let nick = $(this).attr('data-user');
$.post('/services/delete.php',
{
cmd: 'delete',
user: nick
}).then( reply => {
if (reply.status === 'OK') {
alert("User deleted");
}
});
<?php
$cmd = $_POST['cmd'];
switch($cmd) {
case 'delete':
$user = $_POST['user'];
if (deleteUser($user)) {
$reply = [ 'status' => 'OK' ];
} else {
$reply = [ 'status' => 'failure', 'message' => 'Doh!' ];
}
break;
...
header('Content-Type: application/json;charset=UTF-8');
print json_encode($reply);
exit();

Redirecting in codeigniter

I have an issue redirecting to another page in codeigniter, this is my js:
<script type="text/javascript">
$(document).ready(function () {
var url = $('#baseurl').val();
var form = $('#customerinfo');
$('#next').click(function (e) {
if ($("form")[0].checkValidity()) {
// Prevent submit.
e.preventDefault();
//Start loading
var checkbox = $('#Accept');
if (checkbox[0].checked == true)
{
$.post(url + 'customerinfo/next', form.serialize(), function(response) {window.location.href=url + 'paymentinfo';});
}
else
{
$("#errmsg .msg").text("You need to read and accept the terms and conditions before you can continue!");
$("#errmsg").css("display", "block");
}
$(".loading-add-ticket").css("display", "block");
// Send request.
}
else console.log ( "invalid form" );
});
});
</script>
What it does:
When the next button is clicked it submits the form via ajax, the form is then processed on the server and upon completion the user is redirected using the following block of code:
<?php
class CustomerInfo extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
// Write to $title
$this->template->write('title', 'Customer Info');
// Write to $content
$this->template->write_view('content', 'tickets/customerinfo');
// Write to $sidebar
$this->template->write_view('sidebar', 'sidebar');
// Render the template
$this->template->render();
}
function next()
{
if ($_POST) {
if (isset($_POST['Accept']))
{
$data[0] = array(
'TravelInsurance' => $_POST['TravelInsurance'],
'LuggagePayment' => $_POST['LuggagePayment'],
'Donations' => $_POST['Donations'],
'FirstName' => $_POST['FirstName'],
'LastName' => $_POST['LastName'],
'CityTown' => $_POST['CityTown'],
'ContactNo' => $_POST['ContactNo'],
'Address' => $_POST['Address'],
'Accept' => $_POST['Accept']
);
$this->session->set_userdata('customerinfo', $data);
redirect(site_url('paymentinfo'));
}
}
}
}
?>
The problem:
The redirect never happens, when i check the post response using firebug in my browser i notice that the target page has been returned :
What i want: I need the page to be redirected to the target page, i am new to codeigniter so i do not know what i am doing wrong.
current fix:
In the success function on my ajax function i am using javascript to redirect to the next page but i do not want the redirects to be handled on the client side.
Somtimes with forms i prefer to use
header("Location: /Controller/method/value");
i know that's a dirty method but sometimes is helpful

Yii Create a like button using controller action

I'm building a website with Yii framework 1.1 and i'm implementing a portion wherein i have a like button associated with each post.i want to update the content of the like buttons text everytime i click on it without refreshing the page?please help?
EDIT
i did this
`id;
$foo = $data->likes;
echo CHtml::ajaxbutton($foo.' '.'Likes',
array('post/like/'.$id),
array(
'type'=>'POST',
'success'=>'js:function(data){ $.fn.yiiAjaxButton.update("label");}')
);
?>`
still doesnt work
Your View should be like bellow
<?php
$postId = 1; //Your post id
echo CHtml::Button('SUBMIT', array('onclick' => 'getComments(this);', 'data-value' => $postId, 'value' => 'Get Comments'));
?>
And Write your Ajax call some thing like
<script type="text/javascript">
function getComments(obj)
{
$PostID = $(obj).data('value');
$.get('Controller/YourMethod', {id:$PostID}, function(dataJSON)
{
//Get data in JSON formate
},'JSON');
}
</script>
EDIT
If you want to add Ajax call directly to your button, you can do as
<?php
$postId = 1;
echo CHtml::Button('SUBMIT', array('value' => 'Get Comments','onclick' => ''
. '$.get("Controller/YourMethod", {id:'.$postId.'}, function(dataJSON)
{
//Do what ever you want here
},"JSON");'));
?>

Update Bootstrap Thumbail Grid - ajax request

Scenario: I have a view with a twitter bootstrap thumbnail grid that shows the countries. When the user clicks one image, it is supposed to show the cities related to that country, in the same grid (screen).
Technical: First I fill the dataProvider with countries, and then I should send a ajax request with the country id to my controller where it queries the database for cities related to that country and sends the new dataProvider, back to the view where it updates the same thumbnail dataProvider with new data.
Question: How do I do this?
Here is my code:
view with thumbnail declaration (name of the view: _detail)
<?php
$this->widget('bootstrap.widgets.TbThumbnails', array(
'id' => 'detailThumbnails',
'dataProvider' => $dataprov,
'template' => "{items}\n{pager}",
'itemView' => '_thumb',
));
?>
view called in thumbnail "itemView" property (name of the view: _thumb)
<?php
require_once '_detail.php';
?>
<li class="span3">
<a href="#" class="<?php echo "thumbnail".$data['id'] ?>" rel="tooltip" data-title=" <?php echo "Clicar.."; ?>">
<img src="<?php echo Yii::app()->getBaseUrl() . $data['photo'] ?>" alt="">
<a href=
"
<?php
echo $className;
echo $this->createUrl(get_class($data).'/view', array('id' => $data['id']));
?>
"
>
<?php
echo $data['name'].$data['id'];
?>
</a>
<?php
Yii::app()->clientScript->registerScript('thumbClick'.$data['id'],'
$(".thumbnail'.$data['id'].'").click(function(){
var request = $.ajax({
data: {
id : '.$data['id'].'
},
type: "post",
url:"'.Yii::app()->createAbsoluteUrl("tripDetail/getCities").'",
error: function(response, error)
{
alert("Error: " + response + " : " + error);
},
});
$(".thumbnail'.$data['id'].'").ajaxSuccess(function() {
$.fn.yiiListView.update("detailThumbnails");
});
});
');
?>
</a>
</li>
In case of success i need to update the same dataProvider, which is in the view named _detail, hence the require_once. What iam trying to do is pass the data from controller(below) in json and decode here. But i don't know how to build a new data provider from the json response, and dont know either if the encode is properly made. Is it????
controller (just some functions)
public function actionCreate()
{
$session = new CHttpSession;
$session->open();
if(isset($_SESSION['mySession']))
{
$data = $_SESSION['mySession'];
if ($data)
{
if(!isset($_GET['ajax']))
{
$dataprov = new CActiveDataProvider("Country");
$this->render('create',
array(
'dat'=>$data,
'dataprov'=>$dataprov
)
);
}
}
}
}
public function actionGetCities()
{
if(isset($_POST['id']))
{
$cityId = $_POST['id'];
$dataProvider = $this->getCitiesFromDb($cityId);
echo $this->renderPartial('_detail',array('dataprov'=> $dataProvider),true,true);
}
}
public function getCitiesFromDb($cityId)
{
$criteria = new CDbCriteria;
$criteria->select = "*";
$criteria->condition = "b4_Country_id = " . $cityId;
$dataProv = new CActiveDataProvider('City',
array('criteria'=>$criteria));
return $dataProv;
}
If this is not the right way to do this, please let me know
You are mixing Server Side Code and Client side code.
Server Side Code
This code resides on server and upon request it gets executed to provide the valid output to the client. Once it is done it does not maintains any connection with the client
Client Side code
Once request is sent to server client waits for response from server and receives anything sent from server. Once done it disconnects from server until further requests made by user or scripts.
What you did here is <?php$json = CJSON::decode(data)?> php tags are serverside thing and they can not be populated because they appear on client side as in your code. Consider following
If you successfully made the AJAX request you better try changing datatype of Ajax request. I guess you are half way there but you do not know how to decode the JSON received. you can use 'dataType'=>'json' in your ajax request. for more details see Updating fields with Ajax and Json
Hopes this makes life easier
As for update part you can do something like create page and call it via renderpartial and return HTML to your view
public function actionGetCities()
{
if(isset($_POST['id']))
{
$cityId = $_POST['id'];
$dataProvider = $this->getCitiesFromDb($cityId);
echo $this->renderPartial('updateView',array('dataprovider'=> $dataProvider),true,true);//see documentation for third and fourth parameter and change if you like
}
}
and in your view you can just update the div that initially have the orignal grid so no need to use json format.
updateView
<?php
$this->widget('bootstrap.widgets.TbThumbnails', array(
'id' => 'detailThumbnails',
'dataProvider' => $dataProvider,
'template' => "{items}\n{pager}",
'itemView' => '_thumb',
));
?>
Note:
This code is not tested and is given for an idea only.
Ok, yesterday i fixed the problem that was in the jquery. The html generated was right but was not being inserted, when the image refreshed, and then, a little light turned on:
Yii::app()->clientScript->registerScript('thumbClick'.$data['id'],'
$(".thumbnail'.$data['id'].'").click(function(){
var request = $.ajax({
data: {
id : '.$data['id'].'
},
type: "post",
success: function(data) {
$("#detailThumbnails").html(data);
},
url:"'.Yii::app()->createAbsoluteUrl("tripDetail/getCities").'",
error: function(response, error)
{
alert("Error: " + response + " : " + error);
},
});
});
');
The part of the code that says "sucess: "
Thank you very much for all the help you people gave me, specially bool.dev. Your help was precious.

Using Ajax Inside CJUIDialog

I have a CJUIDialog where i load the content of another form using renderPartial. In that form there is an ajax button where it loads another form. That form contains another ajax button where i need to load the previous form inside the dialog itself. I have tried doing it like this. But it doesnt work.
In my controller i have two methods that prints out the two forms like this.
public function actionNewRecipients(){
$customer = new Customer;
$address = new Address;
$content = $this->renderPartial('_form_new',array('customer'=>$customer,'address'=>$address,'guest'=>true),true);
echo $content;
}
public function actionAddRecipients()
{ $content = $this->renderPartial('_form_inner',array(),true);
echo $content;}
And then in one form i have the ajax button like,
echo CHtml::ajaxSubmitButton(Yii::t('New','New Recipient'),CHtml::normalizeUrl(array('customer/newRecipients')),array('success'=>'js: function(data) {
alert("new");
$("#dialog_gift").html(data);
$("#dialog_gift").dialog("option","title","Select Recipient");
}'));
and in the other form i have the ajax button like,
echo CHtml::ajaxSubmitButton(Yii::t('New','New Recipient'),CHtml::normalizeUrl(array('customer/addRecipients')),array('success'=>'js: function(data) {
alert("select");
$("#dialog_gift").html(data);
$("#dialog_gift").dialog("option","title","Select Recipient");
//$("customer-form_inner").attr("action","'.CHtml::normalizeUrl(array('customer/newRecipients')).'")
}'));
And the CJUIDialog looks like,
$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
'id'=>'dialog_gift',
// additional javascript options for the dialog plugin
'options'=>array(
'title'=>$title,
'autoOpen'=>false,
'modal'=>true,
'scrolling'=>'no',
'resizable'=>false,
'scrollable'=>false,
'closeOnEscape' => true,
),
));
echo '<div class="span-24">';
echo $content;
echo '</div>';
$this->endWidget('zii.widgets.jui.CJuiDialog');
Ill be initially loading one forms content.
The first transition happens properly. But after i replace the html content the second transition to load the other view does not happen.
Please let me know if anyone can help.
Thanks
Try setting the 4th parameter of the renderPartial(string $view, array $data=NULL, boolean $return=false, boolean $processOutput=false)-function. By setting $processOutput to true, all necessary scripts (including those to enable ajax-button-functionality) will be included and executed.

Categories