Ajax Pagination cakePHP 3.0 - php

I 've a search filter in a view A, users can choose some values for the research. I want to display the results of the research, without reloading the page, at the bottom of the view in a table.
In a view A, I'va the search filter. In the same view, I'm doing this ajax call :
var tab = new Array();
function updateResult(){
$.ajax({
type:"POST",
url:"<?php echo Router::url(array('controller'=>'AController','action'=>'index'));?>",
data : {dataFVariables: $("select[name='filtreVariable\\[\\]']").map(function(){return $(this).val();}).get()},
dataType: 'json',
async:false,
success: function(tab){
..........
// Creating a table with the data in 'tab'
..........
},
error: function (tab) {
alert('error');
}
});
}
In the action 'index' of my controller, I retrieve a lot of data from the database. With this data, I create a table but the pagination doesn't work on this table..
Indeed, in my controller, I do :
.............
$this->paginate($query);
// the data send to the ajax call
echo json_encode($query);
The results are in the first page of my table but there is nothing in the others pages.
Thank you in advance !!

First Add in your controller :
$condition=array();
$this->paginate = array('conditions' => $condition, 'limit'=>'2');
$users = $this->paginate('YourModelName');
$this->set(compact('users'));
Then add this code in your corresponding ctp file :
<tr><td><?php echo $this->Paginator->prev('<< ' . __('previous', true), array(), null, array('class'=>'disabled'));?></td>
<td><?php echo $this->Paginator->numbers(array( 'class' => 'numbers' ));?></td>
<td><?php echo $this->Paginator->next(__('next', true) . ' >>', array(), null, array('class' => 'disabled'));?></td>
<td colspan="4"></td></tr>

Related

Dependent (Chained) Dropdown in CakePHP 3.8.0 using AJAX

I'm new to CakePHP and ajax. I'm trying to figure out how to utilize AJAX to make dependent (chained) dropdown in CakePHP 3.8.0.
I'm making a few tables for example to learn how to build the chained dropdown menu. I have three tables models, chapters, userinputs. In the Userinputs table, I would to chapter to load based on model. Right now all models and all chapters are shown. This is how they're all connected.
how all three tables are connected
I've been looking at some examples online and tried to apply them into my code but nothing seems to be working. This is my add.ctp of my Userinputs table.
<div class="userinputs form large-9 medium-8 columns content">
<?= $this->Form->create($userinput, ['type' => 'file', 'class' => 'ajax_page']) ?>
<fieldset>
<legend><?= __('Add Userinput') ?><div class="ajax_loading_image"></legend>
<?php
echo $this->Form->control('model_id', ['options' => $models, 'empty' => true, 'id'=>'models']);
echo $this->Form->control('chapter_id', ['options' => $chapters, 'empty' => true, 'id'=>'chapters']);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
I also added this script at the end of add.ctp of Userinputs table
<script>
$("#models").on('change',function() {
var id = $(this).val();
$("#chapters").find('option').remove();
if (id) {
var dataString = 'id='+ id;
$.ajax({
dataType:'json',
type: "POST",
url: '<?php echo Router::url(array("controller" => "Userinputs", "action" => "getChapters")); ?>' ,
data: dataString,
cache: false,
success: function(html) {
//$("#loding1").hide();
$.each(html, function(key, value) {
//alert(key);
//alert(value);
//$('<option>').val('').text('select');
$('<option>').val(key).text(value).appendTo($("#chapters"));
});
}
});
}
});
</script>
In the controller of my Userinputs, I added a public function
public function getChapters()
{
$id = $this->request->data('id');
$chapters = $this->Chapters->find('all', [ 'conditions' => [ 'model_id' => $id ] ]);
echo json_encode($chapters);
}
Please take a look at my codes and please assist me on how to get this working properly. Any help is much appreciated.

Wordpress plugin insert query is not working

I'm calling a wordpress plugin function via a front end page which is working good, the function that i m calling is inserting data into the database but its not working
here is the query i m running(which is not working):
The function is being called on submit as echo value is printed but no data is being inserted
function savedata(){
echo "<pre>";print_r($_POST);exit;
global $wpdb;
$wpdb->insert('questoptions',
array(
'question_id' => $_POST['question_id'],
'text' => $_POST['text']
),
array(
'%s',
'%s'
)
);
die();
return true;
}
here is the function calling this function from front end:
function abc(){
jQuery.ajax({
type: 'POST',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: { action: 'savedata', 'question_id': document.getElementById('question_id').value, 'text': document.getElementById('text').value },
success: function(data){
alert('success');
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
anyone has any idea?
Thanks.
Wordpress ajax function infromation
Add this functions and check your post data is called or not ?
wp_ajax_nopriv_(action) executes for users that are not logged in.
add_action( 'wp_ajax_savedata', 'custom_savedata' );
add_action( 'wp_ajax_nopriv_savedata', 'custom_savedata' );
function custom_savedata() {
global $wpdb;
if(isset($_POST) && !empty($_POST['question_id'])):
$data = ($wpdb->insert('table_name_add_here', array(
'question_id' => $_POST['question_id'],
'text' => $_POST['text'],
)
));
if($data){
echo 'success';
}else{
echo 'not success';
}
else:
echo 'please check post data';
endif;
exit;
}
plz remove second line
echo "<pre>";print_r($_POST);exit;'
so it execute rest of code and return.
if u should try this and also not get solution than u must be check your database table name if table name pretend by 'wp' than u should try wp_ questoptions as table name in query instead of questoptions.
thinks. might be it will help you.

Dynamic drop down box change depend on database in CakePHP

I am new to CakePHP, the problem is I need to create the dynamic values to drop down box the values which are come from mysql.the following is code which i used in controller:
$wires = $this->wire->find('all',array('conditions'=>array('wire_id'=>$wire_id)));
foreach($wires as $key=>$gs) {
$options[$gs['wires']['type_of_wire']] = $gs['wires']['type_of_wire'];
$options1[$gs['wires']['length']] = $gs['wires']['length'];
$options2[$gs['wires']['color']] = $gs['wires']['color'];
}
In ctp
echo $this->Form->input('wire', array('type' => 'select', 'class'=>'dropdn', 'options'=> $options, 'selected'=> $options, 'div'=>false, 'label'=>false,'id'=>'metal'));
echo $this->Form->input('wire', array('type' => 'select', 'class'=>'dropdns', 'options'=> $options1, 'selected'=> $options, 'div'=>false, 'label'=>false,'id'=>'metal'));
echo $this->Form->input('wire', array('type' => 'select', 'class'=>'dropdned', 'options'=> $options1, 'selected'=> $options, 'div'=>false, 'label'=>false,'id'=>'metal'));
Here I create three drop down boxes, but the problem is if I changed the drop down box value type of wire means its dynamically change its correct length and color for rest of the drop down box.
I also tried it ob onchange but I can't.
Use AJAX calling for dynamic drop down list. something like this in your layout/ where you have jquery defined..
$('#metal').change(function() {
var wire= $(this).val();
$.ajax({
type: "POST",
url: "HERE GIVE URL TO YOUR ACTION WHERE YOU FETCH DATA FROM TABLE",
data: { wire: wire , submit: "submit" },
success: function(result){
$("#metal").html(result);
}
});
});
})
Then in your controller, action for ajax call--
public function get_wires()
{
$this->autoRender=false;
$value=$_POST['wire'];
$wire_length = $this->wire->find('list',array('fields' => array('wire_length'),'conditions' => array('wire'=>$value)));
foreach($wire_length as $q)
{
$data[]="<option>".$q."</option>";
}
print_r($data);
}
Then post this value you get into your form in view.ctp page.

Example of calling CakePHP function from jQuery

I am new to CakePHP and I am trying to figure you how to make an asynchronous call from a CakePHP view to a function in the controller. I would like the controller function to return a string and have the view display this string. I would also like to to do this without using helpers. I have been trying to find examples on the web but have been unable to do so. Does anyone have a simple example? I am also using jQuery.
Thanks
CakePHP has a built-in JS Helper to help write aJax functions. The only catch is to include jquery in your head or cake will throw jQuery errors. Heres more information http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html
Your Form:
<?php
echo $this->Form->create('User', array('default'=>false, 'id'=>'YourForm'));
echo $this->Form->input('username');
echo $this->Form->submit('Check Username');
echo $this->Form->end();
?>
The Ajax Function: ('update'=>'#na') is the id of the element you want to update in your view.
<?php
$data = $this->Js->get('#YourForm')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#YourForm')->event(
'submit',
$this->Js->request(
array('action' => 'checkUsername', 'controller' => 'user'),
array(
'update' => '#na',
'data' => $data,
'async' => true,
'dataExpression'=>true,
'method' => 'POST'
)
)
);
echo $this->Js->writeBuffer();
?>
The Function in User Controller
function checkUsername(){
$this->autoRender = false;
$username = $this->User->find('first', array('conditions'=>array('User.username'=>$this->request->data['User']['username'])));
if ( $username == true )
echo 'Username is taken';
else
echo 'Username is not taken';
}
EDIT**
*If you want to use jQuery to do this and not the CakePHP Helper you can use aJax to call an action, then update your element like below*
$('#element').on('click', function() {
$.ajax({
url : '/controller/action',
type: 'POST',
success : function(response){
$('#elementToUpdate').html(response);
}
});
}
});
In your Controller Action you can return the "string" you would like to show in the view
function action(){
$string = 'Show this in the view';
return $string;
}
The above example would be executed when you "Click" an element with an id of "element" then upon "Success" would change element with id of "elementToUpdate" to the String "Show this in the view" Since it was returned from the controller action.

Cannot call method 'update' of undefined Cgridcview

$.fn.yiiGridView.update('sopodetail-grid'+itemcd);
this function it's not running.
It says Cannot call method 'update' of undefined in console.
I have problem when inserting data via ajax gridview not refreshing.
I render multiple grid view with foreach looping, and make each of them unique id with concatenating item_cd.
function validateDetailForm()
{
var jForm = $('#sopodetail-form');
var data = jForm.serialize();
var itemcd = $('#cmbitemcd').val();
$.ajax({
type: 'POST',
url : jForm.attr('action'),
data: data,
dataType:'html',
success:function(data)
{
$(".info").animate({opacity: 1.0}, 3000).fadeOut("slow");
$.fn.yiiGridView.update('sopodetail-grid'+itemcd);
},
error: function(data) { // if error occured
alert('Error occured.please try again');
$('#detail-content').html(data);
},
});
}
this how i can render multiple gridview i concating the id...
foreach($modelSoDet as $modelSoDetObj):
$this->widget('zii.widgets.CDetailView', array(
'data'=>$modelSoDetObj,
'attributes'=>array(
'item_cd',
'item.item_name',
'item.item_desc',
'qty',
'qty_purchased'
)
));
$modelSoPoDetail = new Sopodetail();
$modelSoPoDetail->unsetAttributes();
$modelSoPoDetail->so_cd = $modelSoDetObj->so_cd;
$modelSoPoDetail->item_cd = $modelSoDetObj->item_cd;
$gridid = 'sopodetail-grid'.$modelSoPoDetail->item_cd;
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$modelSoPoDetail->search(),
'summaryText' => '',
'id'=>$gridid,
'columns'=>array(
'type',
'po_cd',
'qty'
)
));
endforeach;
You should simply try with the right syntax :
$('sopodetail-grid'+itemcd).yiiGridView('update');
$.param.querystring is called from the yiiGridView.update and is located in the jquery.ba-bbq.js.
check your HTML source if you have the jquery.ba-bbq.js included...
If the jquery.ba-bbq.js is included then you may be recreating the jQuery object after jquery.ba-bbq.js. E.g. jQuery is loaded more than once....
Source: http://www.yiiframework.com/forum/index.php/topic/9387-cgridview-update/

Categories