how to save checkboxes values in cakephp using ajax? - 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.

Related

Filter posts by their post-type with dropdown menu

I want to filter posts by their post-type.
therefore I have created a dropdown menu where I can select one or multiple post-types.
My question now is: How do I get functionality for my dropdown, because I dont't know how to corespond with the database when the element is in the frontend.
This is my Dropdown-Menu
Using ajax you can filter post.
This is my code for filter post by category (filter post by multiple category selection)
ajax code
<script type="text/javascript">
$('.categorytag').click(function(){
var cokeValue = //you need to pass array of post category id
var data = {
action: 'get_partiblog',
foo: cokeValue
};
$.post('/wp-admin/admin-ajax.php',data,function(response){
$('#filteredblog').html(response);
});
})
</script>
php code
<?php
add_action('wp_ajax_get_partiblog','Getblogcatwise');
add_action('wp_ajax_nopriv_get_partiblog','Getblogcatwise');
function Getblogcatwise(){
$catids = $_POST['foo'];
foreach($catids as $catid){
$args = array(
'post_type'=> 'post',
'orderby' => 'ID',
'category_name' => $catid,
'post_status' => 'publish',
'order' => 'DESC',
'posts_per_page' =>-1 // this will retrive all the post that is published
);
$result = new WP_Query( $args );
if ( $result-> have_posts() ) :
while ( $result->have_posts() ) : $result->the_post();
$link = get_permalink();
echo '<a href="'.$link.'" target="_blank">';
echo '<div class="service-wrapper" style="border:1px solid #367bae;">';
/* if ( has_post_thumbnail() ){
echo '<div><img src="'.the_post_thumbnail("thumbnail").'" alt="Image Missing" rel="lightbox"></div>';
}else{
echo '<div><img src="https://uae.microless.com/cdn/no_image.jpg" alt="" rel="lightbox"></div>';
}*/
$title= get_the_title();
echo '<center><div style="color:#367bae;font-size:22px;font-weight:700;position: relative;margin-top: 25%;padding:5%;">'.$title.'</div></center>';
echo '<div class="service-wrapper-inner">';
//$title= get_the_title();
//echo '<h3>'.$title.'</h3>';
echo '<center><i style="font-size:18px;color:#fff;-webkit-transition: 1s;-moz-transition: 1s;-ms-transition: 1s;-o-transition: 1s; transition: 1s;" class="fa fa-bars"></i></center>';
$excerpt= the_excerpt();
echo '<div class="description"><p>'.$excerpt.'</p></div></div></div></a>';
endwhile;
endif; wp_reset_postdata();
}
}
?>

Chained dropdown menu in cakephp 3

I have 4 tables categories, subcategories, product_types and products. Each is associated with other in following hierarchy.
categories
|- subcategories
|- product_types
|- products
The view of add() action of ProductsController is
<?= $this->Form->create($product, ['type' => 'file', 'class' => 'ajax_page']) ?>
<fieldset>
<legend><?= __('Add Product') ?> <div class="ajax_loading_image"></div></legend>
<?php
echo $this->Form->input('category_id', ['options' => $categories, 'empty' => true]);
echo $this->Form->input('subcategory_id', ['options' => $subcategories]);
echo $this->Form->input('product_type_id', ['options' => $productTypes]);
echo $this->Form->input('product_code');
echo $this->Form->input('SKU');
echo $this->Form->input('title');
echo $this->Form->input('description');
</fieldset>
<?php echo $this->Form->end(); ?>
Right now it is list whole subcategories in the list. I want to load subcategories on change of categories and product_types on change of subcategories using Ajax.
There is no good example I can found for CakePHP 3.x and also some documentation mentioned that js helper has been removed from CakePHP 3
How it can be implemented in CakePHP 3. I'm new to CakePHP and Ajax as well.
Thank You.
ctp file as below. here first of all i give id to field categories,subcategories,producttype and productcode .
<?= $this->Form->create($product, ['type' => 'file', 'class' => 'ajax_page']) ?>
<fieldset>
<legend><?= __('Add Product') ?> <div class="ajax_loading_image"></div></legend>
<?php
echo $this->Form->input('category_id', ['options' => $categories, 'empty' => true,'id'=>'categories']);
echo $this->Form->input('subcategory_id', ['options' => '$subcategories','id'=>'subcategories']);
echo $this->Form->input('product_type_id', ['options' => '$productTypes','id'=>'producttype']);
echo $this->Form->input('product_code',['options'=>'$productcode','id'=>'productcode']);
echo $this->Form->input('SKU');
echo $this->Form->input('title');
echo $this->Form->input('description');
</fieldset> <?php echo $this->Form->end(); ?>
and in your ajax call for subcategories is as below. you can create same ajax call for product_type and product code
<script>
$("#categories").on('change',function() {
var id = $(this).val();
$("#subcategories").find('option').remove();
if (id) {
var dataString = 'id='+ id;
$.ajax({
dataType:'json',
type: "POST",
url: '<?php echo Router::url(array("controller" => "yourcontroller", "action" => "youraction")); ?>' ,
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($("#subcategories"));
});
}
});
}
});
from this code you can get chained dropdown menu. its work for you.

CakePHP Js Helper - Update 3 Dropdown menus dynamically

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".

Yii2 - ActiveForm ajax submit

How can i use ActiveForm with these requirements?
Submit form with ajax.
Before submitting with ajax: Check if error exits.
After submitting: Display error of field under field's input if the server responses unsuccess saving result.
This is your form in view. I prefer use different actions for validation and saving. You can join them into single method.
<?php $form = \yii\widgets\ActiveForm::begin([
'id' => 'my-form-id',
'action' => 'save-url',
'enableAjaxValidation' => true,
'validationUrl' => 'validation-rul',
]); ?>
<?= $form->field($model, 'email')->textInput(); ?>
<?= Html::submitButton('Submit'); ?>
<?php $form->end(); ?>
In validation action you should write. It validates your form and returns list of errrs to client. :
public function actionValidate()
{
$model = new MyModel();
$request = \Yii::$app->getRequest();
if ($request->isPost && $model->load($request->post())) {
\Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
And this is save action. In validate input data for security:
public function actionSave()
{
$model = new MyModel();
$request = \Yii::$app->getRequest();
if ($request->isPost && $model->load($request->post())) {
\Yii::$app->response->format = Response::FORMAT_JSON;
return ['success' => $model->save()];
}
return $this->renderAjax('registration', [
'model' => $model,
]);
}
This code will validate your form in actionValidate() and. For submitting your form via AJAX use beforeSubmit event. In your javascript file write:
$(document).on("beforeSubmit", "#my-form-id", function () {
// send data to actionSave by ajax request.
return false; // Cancel form submitting.
});
That's all.
Submit form with ajax.
Before submitting with ajax: Check if error exits. yii display error if any by default....... :)
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $model backend\models\search\JobSearch */
/* #var $form yii\bootstrap\ActiveForm */
?>
<div class="job-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
//'method' => 'get',
'options' => ['id' => 'dynamic-form111']
]); ?>
<?php echo $form->field($searchModel, 'id') ?>
<?php echo $form->field($searchModel, 'user_id') ?>
<?php echo $form->field($searchModel, 'com_id') ?>
<?php echo $form->field($searchModel, 'job_no') ?>
<?php echo $form->field($searchModel, 'court_id') ?>
<?php // echo $form->field($model, 'case_no') ?>
<?php // echo $form->field($model, 'plainttiff') ?>
<?php // echo $form->field($model, 'defendant') ?>
<?php // echo $form->field($model, 'date_fill') ?>
<?php // echo $form->field($model, 'court_date') ?>
<?php // echo $form->field($model, 'status_id') ?>
<?php // echo $form->field($model, 'created_at') ?>
<?php // echo $form->field($model, 'updated_at') ?>
<div class="form-group">
<?php echo Html::submitButton('Search', ['class' => 'btn btn-primary','id'=>'submit_id']) ?>
<?php echo Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('body').on('beforeSubmit', 'form#dynamic-form111', function () {
var form = $(this);
// return false if form still have some validation errors
if (form.find('.has-error').length)
{
return false;
}
// submit form
$.ajax({
url : form.attr('action'),
type : 'get',
data : form.serialize(),
success: function (response)
{
var getupdatedata = $(response).find('#filter_id_test');
// $.pjax.reload('#note_update_id'); for pjax update
$('#yiiikap').html(getupdatedata);
//console.log(getupdatedata);
},
error : function ()
{
console.log('internal server error');
}
});
return false;
});
});
</script>

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;
});
");

Resources