I have traveled many articles Stack OverFlow but none have solved my problem. I just want to use Ajax with Cake php to refresh a DIV containing the results of my pagination.
Note:
I included the jQuery library.
I called the RequestHandler component:
public $components = array('RequestHandler');
public function beforeFilter() {
if($this->RequestHandler->isAjax()){
$this->layout=null;
Configure::write('debug', 0);
}
}
I checked the presence of a "ajax.ctp" in the layout folder
Here is my search function:
public function searchIndex(){
//debug($this->request->data); die;
$search = $this->request->data['Concessionnaire']['search'];
$this->Paginator->settings = array(
'conditions' => array('Concessionnaire.ville LIKE' => '%'.$search.'%'),
'limit' => 5
);
$data = $this->Paginator->paginate('Concessionnaire');
$this->set('concessionnaires', $data);
$this->render('index');
}
Views :
<div class="row">
<div class="large-12 columns">
<div class="panel">
<h4>Recherchez une ville :</h4>
<?php echo $this->Form->create('Concessionnaire',array('id' => 'textBox', 'type' => 'post','url' => array('controller' => 'concessionnaires', 'action' => 'searchIndex'))); ?>
<?php echo $this->Form->input('search', array('label'=>"",'placeholder'=>'Tapez le nom d\'une ville, puis la touche Entree de votre clavier' ,'id'=>'search')); ?>
<?php echo $this->Form->end(); ?>
</div>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<div class="panel" id="conssR">
<!-- generation vignettes -->
<?php foreach ($concessionnaires as $concessionnaire): ?>
<div class="panel conssPanel radius">
<h4><b><?php echo h($concessionnaire['Concessionnaire']['nom']); ?></b></h4>
<div class="row">
<div class="large-6 columns" style="padding-left: 70px; font-size: 20px;">
<?php echo h($concessionnaire['Concessionnaire']['adresse']); ?><br>
<?php echo h($concessionnaire['Concessionnaire']['cp']); ?>
<?php echo h($concessionnaire['Concessionnaire']['ville']); ?>
<!-- <p>It's a little ostentatious, but useful for important content.</p> -->
</div>
<div class="large-6 columns" style="font-size: 20px; text-align: center;">
Tel: <?php echo h($concessionnaire['Concessionnaire']['tel']); ?><br>
Site: <?php echo h($concessionnaire['Concessionnaire']['website']); ?>
</div>
</div>
<?php
// $map_id = "map_canvas";
// $marker_id = 1;
// $position = "rue du depot, 62000 ARRAS";
// echo $this->GoogleMap->addMarker($map_id, $marker_id, $position);
?>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
I want to reload the DIV "#conssR" with the string results entered in the form "Concessionnaires". For now , when i write something and valid, the controller show me the result by refreshing the page but I just want to recharge the DIV.
Thank you in advance for your help
$this->Paginator->options(array(
'update' => '#conssR',
'evalScripts' => true
));
The code above is not part of function it is part of view files which are in View folder and it creates the proper JavaScript to update the div.
Check : http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html
It is a helper and helper code goes in your view
if($this->request->is('ajax'))
{
$this->render('/Elements/ajax');
}
The above code is used to render ajax.ctp in View/Elements folder which you are not doing at the moment.
Related
I have a page for team members of a company. The team members are rendered with an ACF repeater that has fields for Name, Job Title, and Biography. On the page I would like to render just their Name, and Job Title. If you were to click on a team member, that would open a modal that would render that team members biography.
I have this working, but my approach adds the Biography field to the DOM for each team member, hides it, and passes it into the modal on click. I am wondering if it is possible to pass the Biography field into the modal without having to render the text in the DOM initially and hiding it?
Below is my current code:
<!-- acf repeater -->
<?php if( have_rows('team_member') ): ?>
<?php while( have_rows('team_member') ): the_row();
$name = get_sub_field('name');
$job_title = get_sub_field('job_title');
$biography = get_sub_field('biography');
?>
<div class="team-member">
<div>
<?php echo $name ?>
</div>
<div>
<?php echo $job_title ?>
</div>
<div class="biography" style="display: none;">
<?php echo $biography ?>
</div>
</div>
<?php endwhile; ?>
<!-- modal -->
<div class="modal">
modal
<div class="modal-biography">
</div>
</div>
<?php endif; ?>
<!-- javascript -->
jQuery(function($) {
$('.team-member').on('click', function() {
var modalBiography = $(this).find('.biography').text();
$('.modal-biography').text(modalBiography);
})
});
If you don't need to display the bio div, I'd suggest just putting it into a data-bio attribute:
<div class="team-member" data-bio="<?php echo $biography; ?>">
<div><?php echo $name; ?></div>
<div><?php echo $job_title; ?></div>
</div>
then tweak js a bit to pull this data-bio instead:
jQuery(function($) {
$('.team-member').on('click', function() {
var modalBiography = $(this).data('bio');
$('.modal-biography').text(modalBiography);
})
});
I've a list of team members (custom post type) that I'm calling using WP_Query class. This part is working, however I'm trying to show the description (the_content()) of a team member outside the while loop when clicked on their name. This container (#team-info) is outside the while loop as you can see in the code. Page would ideally scroll to the description container after clicking on the name.
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="team-info"></div>
</div>
</div>
<div class="container mt-15">
<div class="row">
<div class="col-md-12">
<?php
// The Query
$the_query = new WP_Query( array (
'post_type' => 'my_team_sp',
) );
if( $the_query->have_posts() ): $i = 0;
while ( $the_query->have_posts() ) : $the_query->the_post(); $i++; ?>
<div class="col-md-4 <?php echo $i ;?>">
<h4><?php the_title() ;?></h4>
</div>
<?php endwhile;
else :
endif;
/* Restore original Post Data */
wp_reset_postdata();
?>
</div>
</div>
You can Try this with jQuery. See the below Code.
<div class="container mt-15">
<div class="row">
<div class="col-md-12">
<?php
// The Query
$the_query = new WP_Query( array (
'post_type' => 'my_team_sp',
) );
if( $the_query->have_posts() ): $i = 0;
while ( $the_query->have_posts() ) : $the_query->the_post(); $i++; ?>
<div class="col-md-4 <?php echo $i ;?>">
<h4><?php the_title() ;?></h4>
<div style="display: none;"><?php the_content(); ?></div>
</div>
<?php endwhile;
else :
endif;
/* Restore original Post Data */
wp_reset_postdata();
?>
</div>
</div>
jQuery
Add this code in your Js file.
jQuery(document).ready(function($){
$( '.team-name' ).on('click', function(){
var teamInfo = $(this).next().html();
$( '#team-info' ).html( teamInfo );
});
});
I am using CakePHP for an application where I am trying to add some Ajax functionality to update in page content.
JavaScript libraries: Prototype, Scriptaculous, jQuery, jEditable
By default: Load 5 rows and option to load 10 more rows on the page
Editable options: clicking on a field will use the jEditable to allow users to edit the fields and save.
Current situation: When the page loads for the first time, all functionalities work, but when I load 10 more rows, the JavaScript functions stop working.
Here is the index view file which calls an element containing all the entries with the JavaScript functions:
<div id="latestResults" class="wrap">
<?php
echo $this->element('current_entries', array('entries' => $entries));
?>
</div>
<script type="text/javascript">
var clientsInput= <?php echo json_encode($clients); ?>;
$j('.client').editable("<?php echo $this->Html->url(array('controller'=>'entries', 'action'=>'editEntryClient')); ?>/", {
data : clientsInput,
name : 'data[Entry][client_id]',
type : 'select',
onblur : 'submit'
});
//Inline editor for projects
var projectsInput= <?php echo json_encode($projects); ?>;
$j('.project').editable("<?php echo $this->Html->url(array('controller'=>'entries', 'action'=>'editEntryProject')); ?>/", {
data : projectsInput,
name : 'data[Entry][project_id]',
type : 'select',
onblur : 'submit'
});
//Inline editor for tasks
var tasksInput= <?php echo json_encode($tasks); ?>;
$j('.task').editable("<?php echo $this->Html->url(array('controller'=>'entries', 'action'=>'editEntryTask')); ?>/", {
data : tasksInput,
name : 'data[Entry][task_id]',
type : 'select',
onblur : 'submit'
});
//Inline editor for hours spent
$j('.hours_spent').editable("<?php echo $this->Html->url(array('controller'=>'entries', 'action'=>'editEntryHoursSpent')); ?>/", {
name : 'data[Entry][hours_spent]',
onblur : 'submit'
});
//Inline editor for notes
$j('.notesCol').editable("<?php echo $this->Html->url(array('controller'=>'entries', 'action'=>'editEntryDescription')); ?>/", {
name : 'data[Entry][description]',
onblur : 'submit'
});
//Load more
$j('#load_more').click(function(){
//Get last id
var currentNumberOfRows = $j('.row').length;
var newNumberOfRowsToDisplay =currentNumberOfRows + 10;
var urlToGet = "<?php echo $this->Html->url(array('controller'=> 'entries', 'action'=>'displayCurrentEntries')); ?>/" + newNumberOfRowsToDisplay;
$j.get(urlToGet, function(data){
$j('#latestResults').html(data);
});
});
<?php echo $this->Html->script('inpage', array('inline'=>true)); ?>
current_entries.ctp
<?php
$i = 0;
foreach ($entries as $entry):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
$div_id = null;
$div_id = "id='entry_".$entry['Entry']['id']."'";
$row_id = "id='row_".$entry['Entry']['id']."'";
?>
<!-- ROW 1 -->
<div class="row">
<!-- clients -->
<div class="clientCol">
<div class='client result' id='client_<?php echo $entry['Entry']['id']; ?>'><?php echo $entry['Client']['name']; ?></div>
</div>
<!-- projects -->
<div class="projectCol">
<div class='project result' id='project_<?php echo $entry['Entry']['id']; ?>'><?php echo $entry['Project']['name']; ?> </div>
</div>
<!-- tasks -->
<div class="taskCol">
<div class='task result' id='task_<?php echo $entry['Entry']['id']; ?>'><?php echo $entry['Task']['name']; ?> </div>
</div>
<!-- hours -->
<div class="hoursCol">
<div class='hours_spent result' id='hours_spent_<?php echo $entry['Entry']['id']; ?>'><?php echo $entry['Entry']['hours_spent']; ?> </div>
</div>
<!-- Date -->
<div class="dateCol">
<?php echo $entry['Entry']['date_of_task']; ?>
</div>
<!-- notes -->
<div class="notesCol" id='description_<?php echo $entry['Entry']['id']; ?>'>
<?php echo $entry['Entry']['description']; ?>
</div>
<!-- submit -->
<div class="submitCol">
<div class="options">
<a class="duplicate" href=""></a>
<?php echo $ajax->link('', array('controller'=>'entries', 'action' => 'delete', $entry['Entry']['id']), array('class'=>'remove', 'update'=>'latestResults'), 'Are you sure you want to delete this?'); ?>
</div>
</div>
<div class="clear"> </div>
</div>
<?php endforeach; ?>
<!-- //ROW 1 -->
<!-- Load Row -->
<div class="row load">
Load 10 more rows
</div>
<!-- // Load Row -->
When the page loads, all the $j('div.class').editable('') functions work. But whenever it is loading more rows, all these functions stop working alltogether. I might be missing something really simple here, but any help or guidance on this would be brilliant. Note that the loadmore only updates the #latestResults in page through the Ajax call.
Thanks a million in advance.
Regards
Tas
So I have been having trouble finding the right answer to getting each product here displaying in rows of 3. They are now currently only in vertical.
This is how this part was made via Products.shoe_home (a view)
<div class="container-fluid">
<div class="row-fluid">
<div class="span4">
<?php
foreach ($products as $product): ?>
<h2><?php echo h($product['Product']['p_name']); ?> </h2>
<p><?php echo h($product['Product']['p_description']);?> </p>
<div style ="padding-right: 5em">
<?php
if (isset($product['Product']['p_image'])) {
echo $this->Html->image($product['Product']['p_image']);
} else {
echo "No Image Available";
}
?>
</div>
<p>
SHOE SIZE: <?php echo h($product['Product']['p_size']); ?>
</p>
<?php echo $this->Html->link(__('View Details >>'),
array(
'controller' => '/shoepages/',
'action' => 'shoe_view',
$product['Product']['id']),
array('class' => 'btn'));
?>
<?php endforeach; ?>
</div><!--/span-->
</div><!--/row-->
</div>
Unfortunately, I seem to be not allowed to post an image at the moment, so I apologise in advance. Any ideas would be appreciated. The data works on my end.
I included an autocomplete widget inside my view which initially(first page load) works fine and i make an ajax call to update the CListView inside my main page and thats where my autocomplete doesnt show completions(the input box is there but when the user type no suggestion is loaded)..i have seen a lot of issue about using renderPartial and ajax calls not working...anyone with a good solution or please suggest me..
here is my main view that is being refreshed by ajaxcall on the same page..
<div id="top" class="row-fluid" style="margin:0 30 auto 30; ;width:100%;">
<?php
?>
<div id="messages" style="width:35%!important;float:left;margin-left:100px;margin- right:20px!important;position:relative; overflow: hidden;">
<?php
$this->renderPartial('ajaxindex',array('dataProvider'=>$dataProvider),false,true);
?>
<!--end of portlet"-->
</div>
<!--end of messages-->
<div id="nav-panel" class="portlet" style="float:left!important;
width:40%!important;border:1px;box-shadow: 10px 10px 5px #888888;" >
<div class="panel panel-success portlet-decoration">
<!-- Default panel contents -->
<div class="panel-heading">
Filtering Panel >> Rwanda
</div>
</div>
<table class="table table-condensed">
<tr>
<th>Province</th>
<th>Critical</th>
<th>Attention</th>
<th>Normal</th>
<th>Nothing</th>
<th>error</th>
<th>count</th>
</tr>
<?php
$i=1;
$countNothing=0;
$countNormal=0;
$countAttention=0;
$countCritical=0;
$countError=0;
$countAll=0;
foreach($messagesByProvinces as $messagesByProvince){
$province=Province::Model()->findByPk($i);
$provinceParams=null;
$messageParams=null;
$critical=0;
$attention=0;
$normal=0;
$nothing=0;
$error=0;
$count=count($messagesByProvince);
foreach($messagesByProvince as $message){
$countAll++;
if($message->indice==0){
$nothing++;
$countNothing++;
}
elseif($message->indice==1){
$normal++;
$countNormal++;
}
elseif($message->indice==2){
$attention++;
$countAttention++;
}
elseif($message->indice==3){
$critical++;
$countCritical++;
}
else {
$error++;
$countError++;
}
}
if($filter!==null){
$provinceParams=array('message/getProvincereport','id'=>$province->id,'start_date'=>$filter['start_date'],'end_date'=>$filter['end_date']);
$messageParams=array('message/LoadMessages','province_id'=>$province->id,'start_date'=>$filter['start_date'],'end_date'=>$filter['end_date']);
}
else {
$provinceParams=array('message/getProvincereport','id'=>$province->id);
$messageParams=array('message/LoadMessages','province_id'=>$province->id);
}
echo "<tr><td>".CHtml::link($province->name,$provinceParams)."</td>
<td><span class='badge badge-important'>".CHtml::ajaxLink($critical,$this->associate('indice',3,$messageParams),array('update'=>'#messages','success'=>'js:function(data){
var $response=$(data);
var newData=$response.find(".container-fluid").html();
$("#messages").html(newData);
} '))."</span></td>";
Here is the view that is rendered in renderPartial
<script>
function showInput(id){
if(document.getElementById('message-body-'+id).style.display=='block')
document.getElementById('message-body-'+id).style.display='none';
else
document.getElementById('message-body-'+id).style.display='block';
;
}
</script>
<?php
/* #var $this MessageController */
/* #var $dataProvider CActiveDataProvider */
?>
<div id="portlet-messages" class="portlet" style="float:left!important;
width:100% !important;max-height:450px;overflow:auto;
overflow-x:hidden;" >
<div class="panel panel-primary portlet-decoration">
<!-- Default panel contents -->
<div class="panel-heading">
<i class="icon-envelope"></i> Messages
</div>
</div>
<table class="table table-striped">
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'summaryText'=>'',
'enablePagination'=>false,
'itemView'=>'_ajaxview',
)); ?>
</table>
</div>
and the the embed view that contains the bogus code of from CAutoComplete Widget..
<?php
$indiceDisplay='Error';
$label="label-default";
if($data->indice==0){
$indiceDisplay="Nothing";
$label="label-info";
}
elseif($data->indice==1){
$indiceDisplay="Normal";
$label="label-success";
}
elseif($data->indice==2){
$indiceDisplay="Attention";
$label="label-warning";
}
elseif($data->indice==3){
$indiceDisplay="Critical";
$label="label-important";
}
else{
$indiceDisplay="Error";
$label="label-default";
}
echo "<tr class='view' >";
?>
<td>
<?php
echo CHtml::encode(User::Model()->findByPK($data->user_id)->names);echo "<br/></br>";
?>
</td>
<td>
<?php
echo "<b>";
echo CHtml::encode( date_format(new DateTime($data->date), 'g:ia \o\n l jS F Y'));?>
<?php
echo " ";
echo " ";
$linkText="<span class='label ".$label." '> ".$indiceDisplay." </span>";
echo CHtml::link($linkText,array('message/index','indice'=>$data->indice));
echo"</br>";
?>
</b>
</br>
<?php echo CHtml::encode($data->content); ?>
<br />
<?php
echo " <b>Location :</b> ".CHtml::link(Province::Model()->findByPk($data- >province_id)->name,array('message/index','province_id'=>$data->province_id))." ".Chtml::link(District::Model()->findByPk($data->district_id)- >name,array('message/index','district_id'=>$data->district_id))." ".CHtml::link(Sector::Model()->findByPk($data->sector_id)- >name,array('message/index','sector_id'=>$data->sector_id))." ".CHtml::link(Cell::Model()- >findByPk($data->cell_id)->name,array('message/index','cell_id'=>$data->cell_id))." ";
?>
<div id="results-<?echo $data->id;?>">
</div>
<?php echo "<div id='message-body-".$data->id."' style='font-size:12px;display:none;'>";?>
<div class="input-append">
<span>Add Category</span>
<?php $this->widget('CAutoComplete', array(
'model'=>$data,
'attribute'=>'category',
'url'=>array('message/suggestCategory'),
'multiple'=>true,
'htmlOptions'=>array('style'=>'height:11px;font-weight: bold;','maxlength'=>255,'value'=>$data->category,'id'=>'category-'.$data->id,))); ?>
<?php echo CHtml::ajaxSubmitButton('Save',$this- >createUrl('message/categorize',array('id'=>$data->id,'category'=>'js:function(){return $("#category-'.$data->id.'").val();}')),
array(
'type'=>'post',
'data'=>array('category'=>'js:function(){return $("#category-'.$data->id.'").val();}'),
'success'=>'function(data) {
if(data.status=="success"){
$("#results-'.$data->id.'").html(data);
$("#message-body-'.$data->id.'").style.display="none";
}
else{
$("#results-'.$data->id.'").html(data);
document.getElementById("message-body-'.$data->id.'").style.display="none";
}
}',
),array('id'=>'mybtn-'.$data->id,'class'=>'btn btn-small btn- primary','style'=>'height:21px'));
?>
</div>
</div>
</td>
<td>
<a class="btn btn-small" onclick="showInput(<?php echo $data->id;?>);"><i class="icon icon- edit"></i>
</a>
</td>
</tr>
here is the method that is called through the ajax call to update the message div in the main page posted at the begining of the code..
public function actionLoadmessages()
{ $criteria=$this->getCriteria();
if(isset($_REQUEST['indice'])){
$criteria->addCondition('indice=:ind');
$criteria->params['ind']=$_REQUEST['indice'];
}
$dataProvider=new CActiveDataProvider('Message',array('criteria'=>$criteria));
$this->layout=null;
$this->render('ajaxindex',array('dataProvider'=>$dataProvider));
}
You should apply post processing of javascript after the ajax call otherwise some javascript functions will not work ..
Your render call should be something like this
$this->renderPartial('ajaxindex',array('dataProvider'=>$dataProvider),false,true);
Refer this page for more info http://www.yiiframework.com/doc/api/1.1/CController#renderPartial-detail
You should also use renderPartial if updating a div only, render will call layout files as well.