Chained dropdown menu in cakephp 3 - ajax

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.

Related

How to add load more button ajax button to this wordpress loop?

<main class="main aktualitasu_saraksta_konteineris" role="main">
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'group_by' => 'date',
'order' => 'DESC',
'ignore_sticky_posts' => 1
);
$query = new WP_Query($args);
?>
<?php if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>
<?php get_template_part( 'parts/loop', 'news' ); ?>
<?php endwhile; endif; wp_reset_postdata();?>
</main>
How to add load more button that load posts with ajax?
You will need to do this in javascript rather than in php look at this https://www.w3schools.com/jquery/jquery_ajax_get_post.asp. You will need to add button in html say
<button id="load_more" type="button">Load More</button>
And then in javascript (this is an example using jQuery)
$("#load_more").click(function(){
$.get("your/route", function(data, status){
//here you can add the data to the page depending on what the data is
});
});
your/route is whatever route you have set in php for fetching more posts

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>

Cakephp ajax insert without using cake ajaxhelper

I am trying to add data in cakephp by ajax without using ajax helper.Here insertion is working fine but problem is after insert data I have failed to see the success massage.Here is my effort.
<script>
$(document).ready(function(){
$('#submit').click(function(){
x=$("#rform").serializeArray();
$.post($("#rform").attr("action"),
x,
function(data)
{
$("#success").html(data);
$("#success").fadeIn();
$("#success").fadeOut(2800);
$("input").val('');
});
$("#rform").submit(function(){
return false;
});
});
});
</script>
Here is the add.ctp code
<?php
echo $this->Form->create('Info',array(
'id' => 'rform'
)); ?>
<fieldset>
<legend><?php echo __('Add Info'); ?></legend>
<?php
echo $this->Form->input('name');
echo $this->Form->input('email');
?>
</fieldset>
<?php
$options = array
(
'label' => 'Add',
'value' => 'Add',
'id' => 'submit'
);
echo $this->Form->end($options);
?>
</div>
<div style="color:green;" id="success">
</div>
Here after add it is repeating insertion page again in bellow.Here I need to show only success massage.If I remove $("#success").html(data); nothing is happening but after insert button name making disappear.How can I add success massage in here ?
I have solved it by little bit change
$("#success").html(data);
to
$("#success").html("Insert Success");
and here I have changed input button tag, I have use direct button here
<button id="submit">Submit </button>

Dynamically loading custom posts by category with AJAX

I'm working on this site:
http://www.bajo.co.uk/2012/
...which shows a toy portfolio on the home page. The toys have different categories: Infant, Vehicles, educational etc. When the user clicks the sidebar menu 'Infant', thumbnails for all toys with the category 'Infant' will be listed on the right.
I currently have this set up by using a different page-template for each category with the following custom loop:
<!-- loop to show products list -->
<?php
$args = array(
'post_type' => 'products',
'orderby' => 'title',
'order' => 'DES',
'posts_per_page' => 8,
'paged' => get_query_var ('page'),
'post_parent' => $parent,
'category_name' => 'educational'
);
?>
<?php query_posts($args); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<li>
<a href="<?php the_permalink() ?>" class="product_image">
<?php echo get_post_meta($post->ID, 'ProductImage', true);?>
<span class="overlay"></span>
</a>
<h3 class="product_tit"><?php the_title();?></h3>
</li>
<?php endwhile; ?>
<?php else :?>
<p>There are no products to display</p>
<?php endif; ?>
Although this works correctly, every time the user selects a category from the menu, the page is refreshed.
I would like to implement this with AJAX so that the page does not refresh and the products (which are a custom post type) are loaded in dynamically whilst maintaining the pagination.
Any pointers on where to start greatly appreciated.
I'm using:
Wordpress 3.5.1
Custom Post Type UI plugin
I still don't have the right to comment, so I put my comment here as an answer maybe it will be helpful.
My approach for such situation is to create a php file file.php which I will address via a parametrer like this file.php?p=infant (fo example)
<?php
$p=$_GET['p'];
require('../../../wp-load.php');
?>
<?php
$my_query = new WP_Query();
$my_query->query(array( 'post__in' => array($p)));
if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post();
?>
<li>
<a href="<?php the_permalink() ?>" class="product_image">
<?php echo get_post_meta($post->ID, 'ProductImage', true);?>
<span class="overlay"></span>
</a>
<h3 class="product_tit"><?php the_title();?></h3>
</li>
<?php
endwhile;
endif;
?>
I will create in addition a javascript function which will manage the ajax call like this:
function f(str)
{
$.ajax({
cache: true,
type: "GET",
timeout: 5000,
url: 'url/to/file.php?p='+str,
success: function(msg)
{
$('#the_div_containing_li').html(msg);
},
error: function(msg)
{
alert("Your browser broke!");
return false;
}
});
}
Note that you should put your li (and the dynamically loaded content in a div , which I called the_div_containing_li). and onClick on your anchor, call the javascript function f(id of this anchor). you can of course assign to each anchor an id via the wordpress loop.

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