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;
}
Related
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);
}
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.
I try to display data on the bootstrap select option with ajax, but after I run the data do not want to appear what is wrong?
function get_value() {
$id = 5;
$q = $this->db->select('*')
->from('tbl_v')
->where('id', $id)
->order_by('id', 'ASC')
->get();
$result = $q->result();
echo json_encode($result );
}
$(".change").change(function(){
var value=$(this).val();
if(value>0){
$.ajax({
url: base_url+"get_value",
type:"POST",
dataType: 'json',
cache: false,
data:{id:value},
success: function(respond){
$(".get-change").html(respond).selectpicker('refresh');
}
})
}
});
Try this...
function OnChangeValue()
{
var pdrp = document.getElementById("yourControlIDHere");
getvalue= pdrp.options[pdrp.selectedIndex].value;
alert(getvalue);
}
The Control
<select id="yourControlIDHere" onchange="OnChangeValue(this)" name="companyname" style="width:100%">
Jquery Code
$(".change").change(function(){
var value=$(this).val();
if(value>0){
$.ajax({
url: base_url+"get_value",
type:"POST",
cache: false,
data:{id:value},
success: function(respond){
$(".get-change").html(respond);
}
})
}
});
Modal Code:
function get_records() {
$id = 5;
$q = $this->db->select('*')
->from('tbl_v')
->where('id', $id)
->order_by('id', 'ASC')
->get();
$result = $q->result();
}
Controller Code:
function get_value(){
$ido = $this->input->post('id');
$data = $this->your-model-name->get_records($ido);
$option = "";
foreach($data as $row){
$option .= "<option value='".$value['ID']."'>".$row[0]->name."</option>";
}
echo $option;
}
You need not have to use JSON encoding. Records will be directly appended to the select box. Hope this can help you.
My view
<?php echo $calendar; ?>
<div id="event_area"></div>
<script type="text/javascript">
$(document).ready(function(){
$('.calendar .day').click(function(){
var day_data= $(this).find('.content').html();
if($(this).find('.content').html()!=null){
$.ajax({
url: "<?php echo base_url('calendar/pass_name')?>/",
method:"POST",
data:{'day_data':day_data},
success:function(data){
$('#event_area').html(data);
}
})
My controller:
function pass_name(){
$name=$this->input->post('day_data');
$result=$this->load->model('calendar_model')->get_description($name);
$data['calendar'] = $result;
echo json_encode($data);
}
My model:
function get_description($name){
$query = $this->db
->select('description')
->from('calendar')
->where('name',$name)
->get();
return $query->result();
}
This is an example of the result I am getting in my view.
{"calendar":[{"description":"test description\r\nwww.google.com</a>"}]}
How can I make it better, for instance displaying "test description.." without the characters?
Thanks in advance.
In your ajax success function replace the code as follow
success:function(data){
var obj = $.parseJSON(data);
var content = '';
$.each(obj.calendar, function(i,v){
content+= '<p>'+v.description+'</p>'; //--> here you can add any tag, class
});
$("#event_area").html(content);
}
Hope this code may solve your problem. If you need any further clarification,
I'm happy to help you.
You have to add dataType:'json' in your ajax code:
$.ajax({
url: "<?php echo base_url('calendar/pass_name')?>/",
method:"POST",
dataType:'json',
data:{'day_data':day_data},
success: function(data){
$('#event_area').html(data);
}
});
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;
}