Cakephp 4 giving 403 error while using ajax - ajax

I am trying to implement cascading drop down box in cakephp 4 using ajax.
I'm getting an 403 error has tried many solutions from google and stack overflow from htaccess till syntax error and logical error can anyone please help trying since long.
Here is my code:
Add.php
<?php echo $this->Form->control('groups',['options' => $groups],array('id'=>'GroupId'));
echo $this->Form->input('user_id',array('id'=>'UsersId'));
?>
<?= $this->Form->button(__('Submit'),array('id'=>'post')) ?>
<?= $this->Form->end() ?>
<?php echo $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js');?>
<script type="text/javascript" >
$(document).ready(function(){
$("#groups").change(function(){
var deptid = $(this).val();
//var path="<?php echo $this->Url->webroot ?>/Users/getbygroup";
$.ajax({
url: '../Users/getbygroup',
type: 'POST',
data: deptid,
dataType: 'json',
cache: false,
contentType: false,
success:function(response){
var len = response.length;
$("#UserId").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#UserId").append("<option value='"+id+"'>"+name+"</option>");
}
}
});
});
});
</script>
Add action in files controller:
public function add()
{
$this->loadModel('Users');
$this->loadModel('Groups');
$this->set('groups', $this->Groups->find('list'));
$result = $this->Users->find('all'); // returns query object
$data = $result->toArray(); // converts query object to key value array
$file = $this->Files->newEmptyEntity();
if ($this->request->is('post')) {
$file = $this->Files->patchEntity($file, $this->request->getData());
if ($this->Files->save($file)) {
$this->Flash->success(__('The file has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The file could not be saved. Please, try again.'));
}
$this->set(compact('file'));
}
getbygroup function in users controller:
public function getbygroup() {
$fname= $this->request->getData('deptid');
$this->viewbuilder()->layout = 'ajax';
$users = $this->Users->find('list', array(
'conditions' => array('Users.group_id' => $fname),
'recursive' => -1));
$this->set('users', $users);
}

Related

update status from active to inactive using codeigniter

Hi when i want to update my status using a button from inactive to active through ajax method so i have written some code i dont know wether it is right or wrong but status is not updating
This is sample code, This should work
Controller:
public function update_status(){
$status = $this->input->post('status');
$course_id = $this->input->post('id');
$this->CoursesModel->update_course_status($course_id,$status);
}
Model:
public function update_course_status($course_id,$status){
$data['status'] = $status;
$this->db->where('course_id', $course_id);
$this->db->update('courses',$data);
}
Script:
$(document).on('click','.status_checks',function()
{
var status = ($(this).hasClass("btn-success")) ? '1' : '0';
var msg = (status=='0')? 'Deactivate' : 'Activate';
if(confirm("Are you sure to "+ msg))
{
var current_element = $(this);
var id = $(current_element).attr('data');
url = "<?php echo base_url().'index.php/Dashboard/update_status'?>";
$.ajax({
type:"POST",
url: url,
data: {"id":id,"status":status},
success: function(data) {
// if you want reload the page
location.reload();
//if you want without reload
if(status == '1'){
current_element.removeClass('btn-success');
current_element.addClass('btn-danger');
current_element.html('Deactivate');
}else{
current_element.removeClass('btn-danger');
current_element.addClass('btn-success');
current_element.html('Activate');
}
} });
}
});
HTML:
<button type="button" class="status_checks btn <?php echo ($element->status == 1) ? "btn-danger" : "btn-success"; ?> "><?php echo ($element->status == 1) ? "Deactivate" : "Activate"; ?></button>
I guess you should put some info in $data like so
$data['status'] = $status;
$this->db->where('course_id', $course_id);
$this->db->update('courses', $data);
Hope it solves the problem !

Wordpress ajax request returns 0 in my infinite scroll script

I'd like to implement a very customized infinite scroll. But that comes later, cause i'm already stuck at the ajax request. What's wrong with my code (i get alwas a '0' response even though i have die() in the php function and added nopriv ...)??
my header.php:
<script type="text/javascript">
var count = 2;
var total = <?php echo $wp_query->max_num_pages; ?>;
jQuery(window).scroll(function(){
if (jQuery(window).scrollTop() == jQuery(document).height() - jQuery(window).height()){
if (count > total){
return false;
}else{
loadArticle(count);
//viewsite();
}
count++;
}
});
function loadArticle(pageNumber) {
jQuery.ajax({
url: ajaxurl,
type:'POST',
data: {
action: 'ozinfinite_scroll',
page_no: pageNumber
},
success: function(html){
jQuery("#inf-cont-1").append(html);
}
});
return false;
}
</script>
functions.php:
function ozinfinite_scroll(){
// $loopFile = $_POST['loop_file'];
$paged = $_POST['page_no'];
$posts_per_page = get_option('posts_per_page');
# Load the posts
query_posts(array('paged' => $paged ));
get_template_part( 'contentoz', 'blog' );
die();
}
add_action('wp_ajax_ozinfinite_scroll', 'ozinfinite_scroll'); // for logged in user
add_action('wp_ajax_nopriv_ozinfinite_scroll', 'ozinfinite_scroll'); // if user not logged in
function add_ajaxurl_cdata_to_front(){ ?>
<script type="text/javascript"> //<![CDATA[
ajaxurl = '<?php echo admin_url( 'admin-ajax.php'); ?>';
//]]> </script>
<?php }
add_action( 'wp_head', 'add_ajaxurl_cdata_to_front', 1);
thanks for your help!!
According to the docs http://codex.wordpress.org/AJAX_in_Plugins
you should have something like
echo $someValue
before wp_die() or die()

CakePHP-2.4 : subcategories according to categories by ajax

I am trying to get subcategories according to categories by ajax.So I have sent data in controller by ajax get method like bellow code in add.ctp
$('document').ready(function(){
$( "#division" ).change(function() {
var value=$('#division').val();
$.get("<?php echo Router::url(array('controller'=>'userStoreSelections','action'=>'add'));?>",{list:value},function(data){
$('.districts').html(data);
alert(data);
});
});
});
In controller in find methods when I am writing bellow code It's working fine.
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list',array(
'conditions'=>array('mad_divisions_id'=>3)
));
But when I give the value that I have sent by ajax it's not working.I have written like this
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list',array(
'conditions'=>array('mad_divisions_id'=>"$list")
));
It showing the query like this
SELECT `MadDistricts`.`id`, `MadDistricts`.`name` FROM `store`.`mad_districts` AS `MadDistricts` WHERE `mad_divisions_id` IS NULL
After select categories nothing change in query.I have tested ajax code there is no problem to send value.
For more specific this is the add action code
public function add() {
if(isset($this->request->query['list'])){
$search = $this->request->query['list'];
echo $search;
}
else{
$search = '';
}
if ($this->request->is('post')) {
$this->UserStoreSelection->create();
if ($this->UserStoreSelection->save($this->request->data)) {
$this->Session->setFlash(__('The user store selection has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user store selection could not be saved. Please, try again.'));
}
}
$madDivisions = $this->UserStoreSelection->MadDivisions->find('list');
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list',array(
'conditions'=>array('mad_divisions_id'=>"$list")
));
$madAreas = $this->UserStoreSelection->MadAreas->find('list');
$users = $this->UserStoreSelection->Users->find('list',array('fields' => array('id','username')));
$madStores = $this->UserStoreSelection->MadStores->find('list',array('fields' => array('id','store_name')));
$this->set(compact('madDivisions', 'madDistricts', 'madAreas', 'users','madStores'));
}
You need to change your add.ctp file code like as :
$('document').ready(function () {
$("#division").change(function () {
var value = $(this).val();
$.ajax({
url: '<?php echo Router::url(' / ',true);?>userStoreSelections/subcategories',
type: "POST",
dataType: 'json',
data: 'category=' + id,
success: function (res) {
var html = '<option>Sub Category</option>';
if (res.flage == true) {
html = res.data;
}
$('.districts').html(html);
}
});
});
});
Than create a function in your userStoreSelections for get sub categories as
public function subcategories() {
$response = array('flage' => false);
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list', array(
'conditions' => array('mad_divisions_id' => $this->request->data['category'])
));
$options = "<option>Subcategories</option>";
if ($states) {
$response['flage'] = true;
foreach ($madDistricts as $id => $name) {
$options .= "<option value='" . $id . "'>" . $name . "</option>";
}
$response['data'] = $options;
}
echo json_encode($response);
exit;
}

Remove product in the cart using ajax in woocommerce

I would like to remove the product in the woocommerce cart using ajax without click the link.
If you have encounter this kind of functionality, please help us.
add_action( 'wp_footer', 'add_js_to_wp_wcommerce');
function add_js_to_wp_wcommerce(){ ?>
<script type="text/javascript">
jQuery('.remove-product').click(function(){
var product_id = jQuery(this).attr("data-product_id");
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: "/wp-admin/admin-ajax.php",
data: { action: "product_remove",
product_id: product_id
},success: function(data){
console.log(data);
}
});
return false;
});
</script>
<?php }
add_action( 'wp_ajax_product_remove', 'product_remove' );
add_action( 'wp_ajax_nopriv_product_remove', 'product_remove' );
function product_remove() {
global $wpdb, $woocommerce;
session_start();
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item){
if($cart_item['product_id'] == $_POST['product_id'] ){
// Remove product in the cart using cart_item_key.
$woocommerce->cart->get_remove_url($cart_item_key);
}
}
print_r($woocommerce->cart->get_cart());
//echo json_encode(array('status' => 0));
exit();
}
you could use the WC_Cart set_quantity method
And do as this in your php:
$cart = WC()->instance()->cart;
$id = $_POST['product_id'];
$cart_id = $cart->generate_cart_id($id);
$cart_item_id = $cart->find_product_in_cart($cart_id);
if($cart_item_id){
$cart->set_quantity($cart_item_id,0);
}
use this :
$cart = $woocommerce->cart;
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item){
if($cart_item['product_id'] == $_POST['product_id'] ){
// Remove product in the cart using cart_item_key.
$cart->remove_cart_item($cart_item_key);
}
}
Try this one :
foreach ( $woocommerce->cart->cart_contents as $cart_item_key => $cart_item ) {
if($cart_item['product_id'] == $product_id){
unset($cartdetails->cart_contents[$cart_item_key]);
}
}

twitter bootstrap and codeigniter not working

I'm want to create an autosuggest field using twitter bootstraps typeahead plugin. here is my current code. It returns 500 Internal Server Error in inspect elements console. I think the problem is in model. Please help me. Thanks in advance.
view: register
<script type="text/javascript">
$(function() {
$('#office').typeahead({
source: function(typeahead, query) {
$.ajax({
url: "<?php echo base_url('main/get_offices'); ?>",
type: "post",
data: "search=" + query,
dataType: "json",
async: false,
success: function(data) {
typeahead.process(data);
}
});
}
});
});
controller: main
public function get_offices() {
$this->load->model('offices');
$data = $this->offices->get();
echo json_encode($data);
}
model: offices
public function get() {
$office = $this->input->post('search');
$this->db->select('name');
$this->db->from('departments');
$this->db->like('name', $office);
$query = $this->db->get();
$office_array = array();
foreach ($query->result() as $row) {
$office_array = $row->name;
}
//$data['office'] = $office_array;
return $office_array;
}
I tried your code with typeahead in the function parameters but that doesn't seem supported.
I rewrote your code to remove typeahead and return the result outside the scope of the ajax call.
$('#office').typeahead({
source: function(query) {
var result = [];
$.ajax({
url: "<?php echo base_url('main/get_offices'); ?>",
type: "post",
data: "search=" + query,
dataType: "json",
async: false,
success: function(data) {
alert(data); // verify that you actually get data from the model
result = data;
}
});
return result;
}
});
The model function get seems to have a typo, at this part
$office_array = array();
foreach ($query->result() as $row) {
$office_array = $row->name;
}
It should be $office_array[].
$office_array = array();
foreach ($query->result() as $row) {
$office_array[] = $row->name;
}

Resources