missing view file with ajax post method - ajax

I have trying to filter record form database in cakephp. I am using ajax post method to fetch details on same page.But error is missing view file .Here is my controller .
public function userfunddetails(){
$this->autoLayout = false;
$userid = $this->request->data('userid');
$startdate = $this->request->data('startdate');
$startdate = date('Y-m-d', strtotime($startdate));
$enddate = $this->request->data('enddate');
$enddate = date('Y-m-d', strtotime($enddate));
$conditions = array(
array('Recharge.add_date >= ' => $startdate, 'Recharge.add_date <=' => $enddate),
'Recharge.user_id =' => $userid
);
$data = $this->Recharge->find('all',array('conditions'=>$conditions));
$this->set('data', $data);
}
And here is my ajax code . Same thing working on with other function.
I do not know what happen .But same code working for other module.
<script>
$(document).ready(function(){
$('#frm_rechargeHistory_process').submit(function(){
var userid = $("#userid").val();
var startdate = $("#startdate").val();
//alert(startdate);
// var startdate = new Date($('#startdate').val());
//var startdate = $("#startdate").datepicker({ dateFormat: 'yyyy-mm-dd' }).val();
// var enddate = $("#enddate").val(); // Call ajax for pass data to other place
//var enddate = new Date($('#enddate').val());
var enddate = $("#enddate").datepicker({ dateFormat: 'yyyy-mm-dd' }).val();
// alert(enddate);
var dataString = 'userid='+ userid + '&startdate='+ startdate + '&enddate='+ enddate;
if(userid==''||startdate==''||enddate=='')
{
alert("Please Fill All Fields");
}else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "userfunddetails",
data: dataString,
cache: false,
success: function(result){
//alert(result);
$('#txtHint').html(result);
}
});
}
return false;
});
});
</script>

Please check, If it is helpful for you.
In this case,there are two options:
First, you can create the ctp file here: YOURCONROLLER/userfunddetails.ctp and use the $data array.
OR
Second you can put json_encode() in your controller function like below and put die() at the end of function.
<?php echo json_encode(array('data' => $data)); die; ?>
You can found the $data array in your jquery response.

Your ajax call looks for the URL "userHistorydetails" while your function is named "userfunddetails".
Also, shouldn't you use "/controller/userfunddetails" as URL?

Related

Cakephp 4 giving 403 error while using 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);
}

Codeigniter, Ajax: Pass the variable type date from view in controller

I would like to send variables by post method from view to controller using Ajax. My code doesn't work. Can someone help me?
My View: variables change with daterangepicker
var v_start_date = moment().subtract(7, 'days').format("YYYY-MM-DD HH:mm");
var v_end_date = moment().format("YYYY-MM-DD HH:mm");
...
//window.location.replace("<?php echo site_url('consum/ajax_excel');?>" + "/" + v_start_date + "/" + v_end_date);
$.ajax({
url: "<?php echo site_url('consum/ajax_excel')?>",
type: "POST",
dataType : "JSON",
data: {
start_date: v_start_date,
end_date: v_end_date
},
success:function(data) {
},
error : function(data) {
}
});
...
My Controller:
public function ajax_excel() {
//$start_date = $this->uri->segment(5);
//$end_date = $this->uri->segment(6);
$start_date = $this->input->post('start_date');
$end_date = $this->input->post('end_date');
$this->load->library('excel');
$mobiledata = $this->consum->excel_list($start_date,$end_date);
$objPHPExcel = new PHPExcel();
...
My Model:
public function excel_list($start_date,$end_date){
$this->db->select(array('date','consumator','produs','pret','cantitate','total','stare','utilizator'));
$this->db->from('consum as m');
if($start_date !="") if ($end_date !="") {
$this->db->where('date >=', $start_date);
$this->db->where('date <=', $end_date);
}
$this->db->order_by("date", "desc");
$query = $this->db->get();
return $query->result_array();
}
Thanks a lot!
first print_r($_POST) in your controller in order to make sure nothing is misspelled or it's because of encoding or etc. if nothing gets printed check out your routes.php in config folder. if you force CI to route from specific routes you may need to define a new route.

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 !

codeigniter send input file info via ajax

I have a form with 4 fields: title, price, image and category.
When submitted, it inserts the 3 strings into the DB and uploads the image, or returns errors. It all works fine.
However, now I want it to be done via ajax.
It works fine for the title, price and category fields, but how do I pass the info needed from the file field so that codeigniter can upload it?
Right now it keeps saying "You did not select a file to upload."
My controller:
function add_new_product_ajax()
{
// make sure it's the admin, else redirect
if ( ! $this->session->userdata('is_admin') ) {
redirect('admin/login');
exit();
}
// get product name
$pn = $this->input->post('product_title');
// get price
$p = $this->input->post('price');
// get category id
$cid = $this->input->post('categories');
// upload config
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['overwrite'] = TRUE;
// load form validation
$this->load->library('form_validation');
// validate fields
$this->form_validation->set_rules('product_title', 'Product Name', 'trim|required|is_unique[products.name]');
$this->form_validation->set_rules('price', 'Price', 'trim|required|callback_check_price');
$this->form_validation->set_rules('categories', 'Product\'s Category', 'required');
// if validation failed
if ($this->form_validation->run($this) == FALSE)
{
// dummy var
$data['dummy'] = '';
// load categories module to make a select list
$this->load->module('categories/categories');
$data['options'] = $this->categories->categories_select();
// load the view
$this->load->view('new_product_view', $data);
}
else // validation passed
{
// do upload
$this->load->library('upload', $config);
$field_name = "userfile";
// $this->upload->do_upload($field_name);
// try to upload
if ( ! $this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
// load categories module to make a select list
$this->load->module('categories/categories');
$data['options'] = $this->categories->categories_select();
// load the view
$this->load->view('new_product_view', $data);
}
else // upload successful, insert data into table
{
// insert product data
$this->mdl_products->add_product($pn, $p, $cid);
// success msg
$data['msg'] = '<div class=successmsg>The product has been added!</div>';
// load categories module to make a select list
$this->load->module('categories/categories');
$data['options'] = $this->categories->categories_select();
// load the view
$this->load->view('new_product_view', $data);
}
}
}
My ajax ( with missing file value parameter):
$('body').on('click', 'a.submitnewprod', function(e) {
e.preventDefault();
// alert('code');return;
// get product title
var pt = $('#product_title').val();
// get product price
var pp = $('#price').val();
// get category id
var cid = $('#categories').val();
// get userfile ???????
var uf = $('#uploadImage').val();
$.ajax({
type: "POST",
url: site + "admin/add-new-product-ajax",
data: {
product_title:pt,
price: pp,
categories: cid
},
beforeSend: function() {
$('#ajaximg img').addClass('act');
},
success: function(data) {
// $('.results').html(data);
$('#ajax').html(data);
},
complete: function() {
$('#ajaximg img').removeClass('act');
}
});
});
the file html from my view file:
<input id="uploadImage" type="file" name="userfile" size="20" onchange="PreviewImage();" />
What do I need to pass in my ajax call inside data parameter, so that the upload can work normally?
Its not an issue in your PHP its to do with how you are posting the $_FILE field. Instead of grabbing individual form fields try using the form serialize function of jQuery and declare the post as multipart/form-data. There is loads of examples of how to achieve this on SO but should look a bit like this...
var myData = $('#your_form').serialize();
$.ajax({
type: "POST",
contentType:attr( "enctype", "multipart/form-data" ),
url: " URL Goes Here ",
data: myData
...

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

Resources