I have a big problem with Cakephp 3.4
This is my controller:
//$id=$_POST["idString"]; ---- how can i do this in cakephp?
$id = $this->request->data('idString');
$posts = $this->Posts->find('all', array(
'conditions' => array(
'Animal_id' => $id
)
));
$this->set(compact('posts'));
And this is my script
$(document).ready(function() {
$(".dropdown-item").click(function(){
idString = $(this).attr("value");
alert(idString);
$.ajax({
type: "POST",
url: "<?php echo \Cake\Routing\Router::url(array('controller' => 'MyControllerName', 'action' => 'index')); ?>",
data: "idString="+idString,
success: function(result){
$("#show").html(result);
}
});
});
});
And this is my index :
<?php foreach($posts as $post):?>
<li><?= $post->title, $post->text; ?></li>
<?php endforeach ?>
<div id="show">
<--show id-->
</div>
And error that I have is
Deprecated (16384): Controller::$layout is deprecated. Use $this->viewBuilder()->setLayout() instead. [CORE\src\Controller\Controller.php, line 383]
And it returns me one div 2 time.
Cakephp 3.4 have in src/Template/Layout/ajax.ctp look there if don't have $this->fetch('content'); if yes then delete it or comment.
Related
I created a form with php with js on change in the radio buttons:
<?php echo $this->Form->create(null, ['id' => 'filter']); ?>
<?php foreach ($categorias as $key => $value) { ?>
<label class="alignRadio">
<?php echo $this->Form->radio('categoria', [$value->titulo => ''], ['hiddenField' => false, 'class' => 'formRadio switch-inputs', 'label' => false]) ?>
<span class="radio">
<?php echo $this->Html->image('/content/categories/' . $value->icone, ['class' => 'icon']);?>
<?php echo $value->titulo; ?>
</span>
</label>
<?php } ?>
<?php echo $this->Form->end(); ?>
on my default.php, I'm calling the csrfToken:
<?php echo $this->Html->scriptBlock(sprintf(
'var csrfToken = %s;',
json_encode($this->request->getAttribute('csrfToken'))
)); ?>
and then the ajax with js
$(function() {
$(".switch-inputs").on('change', function() {
var categoria = $(this).val();
$.ajax({
url: 'blog/filtrar',
type: 'post',
headers: {
'X-CSRF-Token': csrfToken,
},
data: {
'categoria': categoria,
},
beforeSend: function() {
$('#posts div').fadeOut(400).remove(400);
},
success: function(data) {
if (data) {
$('#posts').fadeOut(0).html(data).fadeIn(200);
}
}
});
});
});
I'm also unlocking the action on the blog controller:
$this->FormProtection->setConfig('unlockedActions', ['carregar', 'filtrar']);
and loading the FormProtection on the AppController:
$this->loadComponent('FormProtection');
But i'm still getting this error, here's the error log:
2022-07-12 18:24:07 error: [Cake\Http\Exception\BadRequestException] `_Token` was not found in request data. in /******/vendor/cakephp/cakephp/src/Controller/Component/FormProtectionComponent.php on line 143
Stack Trace:
- /******/vendor/cakephp/cakephp/src/Controller/Component/FormProtectionComponent.php:97
- /******/vendor/cakephp/cakephp/src/Event/EventManager.php:309
- /******/vendor/cakephp/cakephp/src/Event/EventManager.php:286
- /******/vendor/cakephp/cakephp/src/Event/EventDispatcherTrait.php:92
- /******/vendor/cakephp/cakephp/src/Controller/Controller.php:640
- /******/vendor/cakephp/cakephp/src/Controller/ControllerFactory.php:130
- /******/vendor/cakephp/cakephp/src/Controller/ControllerFactory.php:115
- /******/vendor/cakephp/cakephp/src/Http/BaseApplication.php:317
- /******/vendor/cakephp/cakephp/src/Http/Runner.php:77
- /******/vendor/cakephp/authentication/src/Middleware/AuthenticationMiddleware.php:124
- /******/vendor/cakephp/cakephp/src/Http/Runner.php:73
- /******/vendor/cakephp/cakephp/src/Http/Middleware/CsrfProtectionMiddleware.php:174
- /******/vendor/cakephp/cakephp/src/Http/Runner.php:73
- /******/vendor/cakephp/cakephp/src/Http/Middleware/BodyParserMiddleware.php:162
- /******/vendor/cakephp/cakephp/src/Http/Runner.php:73
- /******/vendor/cakephp/cakephp/src/Routing/Middleware/RoutingMiddleware.php:161
- /******/vendor/cakephp/cakephp/src/Http/Runner.php:73
- /******/vendor/cakephp/cakephp/src/Routing/Middleware/AssetMiddleware.php:68
- /******/vendor/cakephp/cakephp/src/Http/Runner.php:73
- /******/vendor/cakephp/cakephp/src/Error/Middleware/ErrorHandlerMiddleware.php:126
- /******/vendor/cakephp/cakephp/src/Http/Runner.php:73
- /******/vendor/cakephp/cakephp/src/Http/Runner.php:58
- /******/vendor/cakephp/cakephp/src/Http/Server.php:90
- /******/webroot/index.php:40
Request URL: /blog/carregar
I need the ajax to retrieve me the view, but it's not finding the token. I took a look on the html renderized code and the token is there.
Token
Edited for Clarity:
I'm using the misha_filter_function from: https://rudrastyh.com/wordpress/ajax-post-filters.html to filter posts.
The initial array is displaying the correct posts by the location_and_season (made with ACF) tag. But something weird is going on with the second array because when I click my dropdown select to sort the posts by category it's filtering all of the posts within the post type, and effectively ignoring 'tag' => $value,
I'm relatively new to Wordpress PHP and JS, so my Google-Fu hasn't been too helpful since I don't really know what to search. Any help would be appreciated. Thanks!
Here's the filter Code:
<?php
add_action('wp_ajax_myfilter', 'misha_filter_function'); //
wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
function misha_filter_function()
{
$value = get_field('location_and_season');
$args = array(
'post_type' => 'shows',
'tag' => $value,
'posts_per_page' => - 1, // show all posts.
'orderby' => 'name', // we will sort posts by name
'order' => 'ASC'
//$_POST['name'] // ASC or DESC
);
// for taxonomies / categories
// IMPORTANT! Adding && !empty( $_POST['categoryfilter'] ) fixes the no posts found for All Categories
if (isset($_POST['categoryfilter']) &&
!empty($_POST['categoryfilter'])) $args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_POST['categoryfilter']
)
);
$query = new WP_Query($args);
// The Query
query_posts($args);
// The Loop
while (have_posts()):
the_post(); ?>
Here's the front end dropdown code:
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php"
method="POST" id="filter" style="float:right; margin-right: 15px;">
<?php
if ($terms = get_terms(array(
'taxonomy' => 'category',
'orderby' => 'name'
))):
echo '<select name="categoryfilter"><option id="refresh" value="all"
class="dropdown-select">All Topics...</option>';
foreach ($terms as $term):
echo '<option value="' . $term->term_id . '">' . $term->name .
'</option>';
endforeach;
echo '</select>';
endif;
?>
<div class="processing" style="height:30px;"></div>
<input type="hidden" name="action" value="myfilter">
</form>
And the JS
jQuery(function ($) {
$('#filter').change(function () {
var filter = $('#filter');
$.ajax({
url: filter.attr('action'),
data: filter.serialize(), // form data
type: filter.attr('method'), // POST
beforeSend: function (xhr) {
filter.find('.processing').html('<img src="spinner.gif" class="spinner">'); // changing the button label
},
success: function (data) {
filter.find('.processing').text(''); // changing the button label back
$('#response').html(data); // insert data
}
});
$(document).ready(function () {
$('#filter').on("click", function () {
$('.post-section').toggleClass("active");
});
});
return false;
});
I don't see anything that actually calls your php function. Wordpress ajax calls require an action in the data.
$.ajax({
url: filter.attr('action'),
type: filter.attr('method'), // POST
data: {
action: 'misha_filter_function',
categoryfilter: $(select['name ="categoryfilter"]').val()
},
beforeSend: function (xhr) {
filter.find('.processing').html('<img src="spinner.gif" class="spinner">'); // changing the button label
},
success: function (data) {
filter.find('.processing').text(''); // changing the button label back
$('#response').html(data); // insert data
},
failure: function(response){
console.log(response); //Debug only
}
});
Also, do you enqueue the js script with wp_localize_script?
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.
I am creating a codeigniter project where i get number of items from my database and each item has a submit button clicking on which the data are stored into the database using AJAX and jQuery.
Now, the problem is that when i submit any item only the data of 1st form is sent to the method that inserts data to the database please provide some solution regarding the same. my code is as under:
Model:
<?php
class Products_model extends CI_Model{
function get_all(){
$results = $this->db->get('tblUtensils')->result();
return $results;
}
function get($id){
$results = $this->db->get_where('tblUtensils', array('pkItemID' => $id))->result();
$result = $results[0];
return $result;
}
}
?>
View:
<body>
<div id="products">
<?php foreach ($products as $product):
$id=$product->pkItemID;
?>
<li>
<?php echo form_open('shop/add', 'id="form"'); ?>
<div><?php echo form_input('name_' . $id, $product->fldName , 'id='.'"'.'name_' . $id.'"');?></div>
<div><?php echo form_input('desc_' . $id, $product->fldDescription , 'id='.'"'.'desc_' . $id.'"');?></div>
<div><?php echo form_input('rate_' . $id, $product->fldRateMB1 , 'id='.'"'.'rate_' . $id.'"');?></div>
<div><?php echo form_input('Qty_' . $id, 0, 'id='.'"'.'qty_' . $id.'"');?></div>
<?php echo form_hidden('id', $product->pkItemID, 'id="ID"'); ?>
<?php echo form_submit('action', 'Add','id="submit"');?>
<?php echo form_close(); ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<!-- try 2 -->
<script type = "text/javascript">
$(function(){
$('form').submit(function(e){
e.preventDefault(); // <------this will restrict the page refresh
var form_data = {
id: $('#id').val(),
name: $('#name_' + id).val(),
rate: $('#rate_' + id).val(),
qty: $('#qty_' + id).val()
};
$.ajax({
url: "<?php echo site_url('shop/add'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
alert("success");
}
});
return false;
});
});
</script>
</body>
</html>
Controller:
<?php
class Shop extends CI_Controller{
function index(){
$this->load->model('Products_model');
$data['products'] = $this->Products_model->get_all();
$this->load->view('products',$data);
}
function add(){
//$this->load->model('Products_model');
//$product = $this->Products_model->get($this->input->post('id'));
$insert = array(
'id' => $this->input->post('id'),//<-- also not able to get this id from ajax post request
'qty' => $this->input->post('qty'),
'price' => $this->input->post('rate'),
'name' => $this->input->post('name'),
);
$this->cart->insert($insert);//<--insert item into cart
$query// to insert into database
//redirect('shop');
}
}
?>
Many questions have been posted before regarding codeigniter and ajax but none did provide solution to my problem so i am posting this question, appreciate your help.
Change
<?php echo form_open('shop/add', 'id="form"'); ?>
To
<?php echo form_open('shop/add', 'id="form_' . $id . '"'); ?>
This gives different id's for each forms.
I tried many ways of dealing with this and finally the thing that worked for me was as under:
<script type = "text/javascript">
$('.submit').click(function(){
var id = (this.id);
var form_data = { //repair
id: id,
name: $('#name_' + id).val(),
rate: $('#rate_' + id).val(),
qty: $('#qty_' + id).val()
};
$.ajax({
url: "<?php echo site_url('shop/add'); ?>",//repair
type: 'POST',
data: form_data, // $(this).serialize(); you can use this too
success: function(msg) {
alert("success..!! or any stupid msg");
}
});
return false;
});
</script>
I am new in code Igniter so I don't know how to do it. So what my problem is I have a form which I am submitting from ajax. So what I want to do is as the form submit successfully then a notification or a css div class will appear above the form and then disappear it.I don't know how can I perform this as after accepting the parameter from view page to controller I don't know how to send the parameter controller to view or how can I perform all this .Here is my controller:
class categoryController extends CI_Controller {
function index(){
$data['main_content'] = 'categoryView';
$this->load->view('dashboardTemplate/template',$data);
}
function addCategory(){
//getting parameters from view
$data = array(
'cat_name' => $this->input->post('cat_name')
);
$is_ajax = $this->input->post('ajax'); //or use this line
$this->load->model('categoryModel');
$query = $this->categoryModel->addCategories($data);
if ($query && $is_ajax){
$page['main_content'] = 'categoryView';
$page['v'] = '1'; // i dont know how this variable is not accessing in view page by echo $v
$this->load->view('dashboardTemplate/template',$page);
}
else
{
//
}
}}
Here is my view:
<?php
$attributes = array('id' => 'form-horizontal',
'class' => 'form-horizontal'
);
echo form_open('categoryController/addCategory', $attributes);
$cat_name = array(
'name' => 'cat_name',
'id' => 'cat_name',
'class' => 'cat_name');
$button = array(
'name' => 'button',
'id' => 'btn',
'class' => 'btn btn-primary',
'value' => 'submit',
'type' => 'submit',
'content' => 'Submit'
);
?>
<h3>Add Category</h3>
//here i want to do this .. that if form is submitted succesfully then this class will load only and the whole page remain the same
<div> class="alert-heading">sucess or not success!<div>
</div>
<div class="control-group">
<label for="basicround" class="control-label">Category Name:</label>
<div class="controls">
<?php echo form_input($cat_name); ?>
<div class="form-actions">
<?php echo form_button($button); ?></div>
<script type="text/javascript">
$('#btn').click(function() {
var cat_name = $('#cat_name').val();
if (!cat_name || cat_name == 'Name') {
alert('Please enter Category Name');
return false;
}
var form_data = {
cat_name: $('#cat_name').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('categoryController/addCategory'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
</script>
Since it is an Ajax submit, So you need to pass JSON array from controller to view
echo json_encode($page);
Controller
$page['main_content'] = 'categoryView';
$page['v'] = '1'; // i dont know how this variable is not accessing in view page by echo $v
echo json_encode($page);
For the above step, you need to define
data-type:JSON
in your ajax function.
Ajax Function
$.ajax({
url: "<?php echo site_url('categoryController/addCategory'); ?>",
type: 'POST',
data: form_data,
data-type: "json",
success: function(msg) {
// Here you can access the values from controller like msg.v
$('#message').html(msg);
}
});
Based on the response, you can show the success message using
$(".alert-heading").show();