CakePHP Js Helper - Update 3 Dropdown menus dynamically - ajax

i'm using CakePHP 2.6.1
I have a cakephp form to handle accesses with these 3 dropdown menues:
location->facility->department
I want them to be dynamic populated and so i followed this tutorial http://marnienickelson.com/2014/10/11/dynamic-dropdowns-with-cakephp-2-x/
It works well, except one little problem. If i change the "location", the "facility" Dropdown menu is filled correctly, but the "department" menu stays blank...
My AccessesController.php
public function add() {
if ($this->request->is('post')) {
$this->Access->create();
if ($this->Access->save($this->request->data)) {
$this->Session->setFlash(__('The access has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The access could not be saved. Please, try again.'));
}
}
$titles = $this->Access->Title->find('list');
$locations = $this->Access->Facility->Location->find('list');
$systems = $this->Access->System->find('list');
$this->set(compact('titles', 'locations', 'facilities', 'departments', 'systems'));
}
My get_by_location.ctp (and i have an equal file called get_by_facility.ctp)
<?php foreach ($facilities as $key => $value): ?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php endforeach; ?>
And at the end of my add.ctp
<?php
$this->Js->get('#AccessLocationId')->event('change',
$this->Js->request(array(
'controller'=>'facilities',
'action'=>'getByLocation'
), array(
'update'=>'#AccessFacilityId',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
))
);
$this->Js->get('#AccessFacilityId')->event('change',
$this->Js->request(array(
'controller'=>'departments',
'action'=>'getByFacility'
), array(
'update'=>'#AccessDepartmentId',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
))
);
?>
I know the second event'change' isnt recognized and thats why my 3rd dropdown stays blank... Is there an other event then 'change'? Or could i put these two ajax requests in one?

This Blog helped me alot Euromarks blog
I just changed my get_by_location.ctp file:
<?php
if (!empty($facilities)) {
echo '<option value="">' . __('pleaseSelect') . '</option>';
foreach ($facilities as $k => $v) {
echo '<option value="' . $k . '">' . h($v) . '</option>';
}
} else {
echo '<option value="0">' . __('noOptionAvailable') . '</option>';
}
So if first dropdown is changed, the second one will display "please select".

Related

AJAX Search returns "You do not have sufficient permissions to access this page" on non-admin user

I have this demo website that I'm making:
https://theme.artware.gr/
The problem I am facing is on the search functionality. You can click on the right/top side search to see the issue. When I am logged-in as admin, the search works fine, but when I view the page as a guest I get the error: "You do not have sufficient permissions to access this page".
This is my code so far:
// AJAX Search (no WooCommerce)
if ( !class_exists( 'WooCommerce' ) ) {
function simple_search_scripts(){
wp_enqueue_script( 'simple_search', get_stylesheet_directory_uri() . '/js/search.js', array(), '1.0.0', true);
wp_localize_script('simple_search', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ), 'nonce' => wp_create_nonce('ajax-nonce') ));
}
// Create shortcode
function simple_search(){
simple_search_scripts(); ?>
<input type="text" name="keyword" id="keyword" onkeyup="fetch()" placeholder="<?php _e('Αναζήτηση...'); ?>" />
<div id="datafetch"></div>
<?php
}
add_shortcode('simple_search', 'simple_search');
// Fetch data
function simple_search_callback(){
$the_query = new WP_Query( array( 'posts_per_page' => 10, 's' => esc_attr( $_GET['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) : while( $the_query->have_posts() ) : $the_query->the_post();
$myquery = esc_attr( $_GET['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) { ?>
<div class="result-sin">
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' ); ?>
<div class="result-sin-img">
<?php if ($image) { ?>
<img src="<?php echo $image[0]; ?>" width="<?php echo $image[1]; ?>" height="<?php echo $image[2]; ?>" />
<?php } ?>
</div>
<div class="result-sin-tit"><?php the_title();?></div>
<div class="result-sin-txt"><?php the_excerpt();?></div>
</div>
<?php }
endwhile;
wp_reset_postdata();
endif;
die();
}
add_action('wp_ajax_simple_search', 'simple_search_callback' );
add_action('wp_ajax_nopriv_simple_search', 'simple_search_callback' );
}
And the search.js:
function fetch(){
jQuery.ajax({
async: true,
url: myAjax.ajaxurl,
type: 'GET',
data: {
action: 'simple_search',
keyword: jQuery('#keyword').val(),
nonce: myAjax.nonce
},
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
And on the header, I simply call a shortcode [simple_search] . Everything post I read on SO said that the wp_ajax_nopriv_ACTION was missing. But I already have that.
UPDATE
I tried using method GET, that didn't work. I also used: wp_localize_script('simple_search', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ), 'nonce' => wp_create_nonce('ajax-nonce') )); to better enqueue the admin-ajax.php, that didn't work either.
Somewhere In my theme I had require_once('file.php') that had the line below:
if ( !current_user_can( 'manage_options' ) ) { wp_die( __( 'You do not have sufficient permissions to access this page.' ) ); }
When I removed this, the problem was fixed.

Codeigniter Submit multiple rows in database

I'm trying to submit multiple rows in database. And I'm getting this error:
Filename: C:/xampp/htdocs/soluforma_ghm/system/database/DB_query_builder.php
Line Number: 1481
Can you please share some indications to solve my problem.
Thanks in advance.
My view file with AJAX Append. This way I'm adding multiple inputs
// Add options
$.each(response,function(index,data){
$('#sel_depart').append(
'<div class="form-check">'+
'<input type="checkbox" name="formandos_servicos[]" value="'+data['id']+'">'+
'<input type="text" name="nome_funcionario_servicos[]" value="'+data['title']+'" >'+
'<input type="text" name="naturalidade_servicos[]" value="'+data['naturalidade']+'" placeholder="Naturalidade">'+
'<input type="text" name="data_nascimento_servicos[]" value="'+data['data_nascimento']+'" placeholder="Data Nascimento">'+
'<input type="text" name="nacionalidade_servicos[]" value="'+data['nacionalidade']+'" placeholder="Nacionalidade">'+
'<input type="text" name="doc_identificacao_servicos[]" value="'+data['doc_identificacao']+'" placeholder="Documento de Identificacão">'+
'<input type="text" name="validade_identificacao_servicos[]" value="'+data['validade_identificacao']+'" placeholder="Validade CC">'+
'</div>'
);
}
MY Servicos_model. I'm counting $this->input->post['formandos_servicos'] and submit multiple rows.
public function set_servicos($id = 0) {
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array();
$count = count($this->input->post['formandos_servicos']);
for($i = 0; $i < $count; $i++) {
$data[] = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'area_servicos' => $this->input->post('area_servicos'),
'formadores_servicos' => $this->input->post('formadores_servicos'),
'data_servicos' => $this->input->post('data_servicos'),
'nome_servicos' => $this->input->post('nome_servicos'),
'horas_servicos' => $this->input->post('horas_servicos'),
'conteudos_servicos' => $this->input->post('conteudos_servicos'),
'formandos_servicos' => $this->input->post['formandos_servicos'][$i],
'nome_funcionario_servicos' => $this->input->post['nome_funcionario_servicos'][$i],
'naturalidade_servicos' => $this->input->post['naturalidade_servicos'][$i],
'data_nascimento_servicos' => $this->input->post['data_nascimento_servicos'][$i],
'nacionalidade_servicos' => $this->input->post['nacionalidade_servicos'][$i],
'doc_identificacao_servicos' => $this->input->post['doc_identificacao_servicos'][$i],
'validade_identificacao_servicos' => $this->input->post['validade_identificacao_servicos'][$i],
'anotacoes_servicos' => $this->input->post('anotacoes_servicos'),
'categoria_servicos' => $this->input->post('categoria_servicos'),
'visivel_servicos' => $this->input->post('visivel_servicos'),
'utilizador_servicos' => $this->input->post('utilizador_servicos'),
'criado_servicos' => $this->input->post('criado_servicos'),
'modificado_servicos' => $this->input->post('modificado_servicos')
);
}
if ($id == 0) {
return $this->db->insert_batch('servicos', $data);
}
}
You can Use $this->db->last_query(); to know what's query execute to inserted data in database.
with echo()
Thank you for the reply.
I try print_r to check Array data and I get and empty Array
if ($id == 0) {
//return $this->db->insert_batch('servicos', $data);
echo '<pre>';
print_r($data);
echo '</pre>';
die();
}
print_r Result:
Array
(
)
The Array is now working.
I replace [] with () on
$this->input->post[''][$i]
$this->input->post('')[$i]
On [formandos_servicos] => 972, the Array index is correct.
But are incorrect on:
[nome_funcionario_servicos] => Manuel Fonseca Santos
[naturalidade_servicos] => Fornos Algodres
[data_nascimento_servicos] => 1960-11-15
[nacionalidade_servicos] => Portuguesa
[doc_identificacao_servicos] => 1524575 7ZY0
[validade_identificacao_servicos] => 2019-09-04
because I'm counting:
count($this->input->post('formandos_servicos'));
I'm getting a mismatch between input type="checkbox" and the others input type="text" fields.

Clear or reset the wordpress posts pagination while changing filters

I think it is simple, but I don't get it.
This is my filter:
<form class='post-filters'>
<select name="filter">
<?php
$filter_options = array(
'houses' => 'Houses',
'hotels' => 'Hotels',
);
foreach( $filter_options as $value => $label ) {
echo "<option ".selected( $_GET['filter'], $value )." value='$value'>$label</option>";
}
?>
</select>
<input type='submit' value='Filter!'>
</form>
Related PHP to apply the filter to the wordpress query:
<?php
global $destinations;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$destinations = new WP_Query([
'paged' => $paged,
'location' => $location,
'category_name' => urldecode(get_query_var('filter')),
'posts_per_page' => 6
]);
?>
If I do select my "filter" and the result has more than six entries, I use next_posts_link() to see the next six results. The problem is now, if I'm on page 2 or 3 and the other filter has less than e.g. 6 entries, I will see no results while changing my filter.
How do I clear the get variable (/page/2/) while changing my filter?
Example:
category/subcategory/subsubcategory/page/3/?filter=houses
Now I select "filter" hotels
category/subcategory/subsubcategory/page/3/?filter=hotels
and the "/page/3" will not be cleared. So I can not see some posts.
It has been anwsered here:
https://wordpress.stackexchange.com/a/264266
function get_nopaging_url() {
$current_url = $_SERVER[REQUEST_URI];
$pattern = '/page\\/[0-9]+\\//i';
$nopaging_url = preg_replace($pattern, '', $current_url);
return $nopaging_url;
}
You could use this function to remove the pagination in your urls with filters.
See example:
<a href="<?php echo get_nopaging_url(); ?>?filter=houses">

Ajax search and CGridView

I'm trying to implement an ajax search in my CGridView and I'm not having much luck getting it to work.
My Grid:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'talent-grid',
'dataProvider'=>$model->searchTalent(),
'hideHeader'=>true,
'template' => '{pager}{items}{pager}',
'pager'=>array('cssFile'=>'/css/pager.css','header' => '',),
'cssFile'=>'/css/client-grid.css',
'columns'=>array(
array(
'name'=>'talent_id',
'type'=>'raw',
'value'=>'$data->getTalentGridRow($data)',
),
),
)); ?>
Search form:
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
)); ?>
<div class="row">
<?php echo $form->label($model,'full_name',array('class'=>'inline')); ?>
<?php echo $form->textField($model,'full_name',array('size'=>60,'maxlength'=>64)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'gender_id',array('class'=>'inline')); ?>
<?php echo $form->checkBoxList($model, 'gender_id',CHtml::listData(Gender::model()->findAll(), 'gender_id', 'name'),array('separator'=>' ')); ?>
<?php echo $form->error($model,'gender_id'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
The search model:
public function searchTalent() {
$criteria=new CDbCriteria;
$criteria->compare('full_name',$this->full_name,true);
if ($this->gender_id != "") {
$criteria->compare('gender_id',$this->gender_id);
}
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>30,
),
));
}
The javascript:
Yii::app()->clientScript->registerScript('searchTalent', "
$('#search-form form').submit(function(){
$.fn.yiiGridView.update('talent-list', {
data: $(this).serialize()
});
return false;
});
");
The controller:
public function actionClients() {
$model = new Talent('search');
$model->unsetAttributes(); // clear any default values
if (isset($_GET['Talent'])) {
$model->attributes = $_GET['Talent'];
}
$this->render('clients', array(
'model' => $model,
'pages' => 10
));
}
the js submit fires, but the grid doesn't get updated. Not sure why.
You have specified the id of gridview in js as talent-list but the original id is talent-grid as specified in widget initialization call . So change the line as
Yii::app()->clientScript->registerScript('searchTalent', "
$('#search-form form').submit(function(){
$.fn.yiiGridView.update('talent-grid', {
data: $(this).serialize()
});
return false;
});
");

how to save checkboxes values in cakephp using ajax?

I want to save the values of the checkbox using ajax.
Here is my current code that I wish to update to use ajax.
here is the view
<?php $i = 0;
foreach ($summary as $sum) {
?>
<tr class="font-size12">
<td><p><?php echo $sum['posts']['title']; ?></p></td>
<td class="width450"><p><?php echo $sum['posts']['content']; ?></p></td>
<td><p class="margin-left28"><?php echo $sum['members']['username']; ?></p></td>
<td><p><?php echo $sum['posts']['deadline']; ?></p></td>
<?php echo $this->Form->create("Posts", array("action" => "update_checkbox")) ?>
<td>
<?php
echo $this->Form->input('Post.' . $i . '.id', array("type" => "hidden", "label" => false, "value" =>
$sum['posts']['id']))
?>
<?php
echo $this->Form->input('Post.' . $i . '.done', array("type" => "checkbox", "label" => false, "value" => "1", "id" => "idCheck[]", "onclick" => "getboxes()"))
?>
</td>
</tr>
<?php $i++;
}
?>
</table>
<?php echo $this->Form->end() ?>
the javascript
function getboxes(){
$("idCheck[]").click(function(){
$.ajax({
url: '../../../../Controller/PostsController',
data: { action: 'checkingBox' },
type: 'post'
// ,
// success: function(output) {
// alert(output);
// }
});
});
}
the controller
public function update_checkbox() {
// debug($this->data);
$var = $this->Post->saveCheckBox($this->data);
$this->set("result", $var);
}
the model
public function saveCheckBox($checkbox) {
debug($checkbox);
$this->saveAll($checkbox['Post']);
}
edit: I added a listener in the checkbox
According to your current code, there are two ways to store check-boxes values into the database.
Either You will have to manipulate the posted data received into your ajax_method()
and make it the array like below
[Post] => array(
[0] => ....
[1] => ....
);
Then you c an use $this->Post->saveAll($this->request->data);
or you can use the following code to save checkbox values into the database.
echo $this->Form->input('Case.CHECK_ID][', array('type' => 'checkbox'));
Then you can use saveAll() method.

Resources