http://rimi-classified.com/ad-list/west-bengal/kolkata/electronics-and-technology
The above link has a filter in the left. I am trying to use ajax to get city from state. but as the ajax is triggered the entire query is changing.
SELECT * FROM (`ri_ad_post`)
WHERE `state_slug` = 'west-bengal'
AND `city_slug` = 'kolkata'
AND `cat_slug` = 'pages'
AND `expiry_date` > '2014-03-21'
ORDER BY `id` DESC
It is taking the controller name in the query (controller name is pages).
The actual query is:
SELECT *
FROM (`ri_ad_post`)
WHERE `state_slug` = 'west-bengal'
AND `city_slug` = 'kolkata'
AND `cat_slug` = 'electronics-and-technology'
AND `expiry_date` > '2014-03-21'
ORDER BY `id` DESC
// Controller
public function ad_list($state,$city,$category,$sub_cat=FALSE)
{
if($state===NULL || $city===NULL || $category===NULL)
{
redirect(base_url());
}
$data['ad_list'] = $this->home_model->get_adlist($state,$city,$category,$sub_cat);
$this->load->view('templates/header1', $data);
$this->load->view('templates/search', $data);
$this->load->view('ad-list', $data);
$this->load->view('templates/footer', $data);
}
public function get_cities()
{
$state_id = $this->input->post('state');
echo $this->city_model->get_cities($state_id);
}
// Model
public function get_adlist($state,$city,$category,$sub_cat=FALSE)
{
if ($sub_cat === FALSE)
{
$this->db->where('state_slug', $state);
$this->db->where('city_slug', $city);
$this->db->where('cat_slug', $category);
$this->db->where('expiry_date >', date("Y-m-d"));
$this->db->order_by('id', 'DESC');
$query = $this->db->get('ad_post');
}
$this->db->where('state_slug', $state);
$this->db->where('city_slug', $city);
$this->db->where('cat_slug', $category);
$this->db->where('sub_cat_slug', $sub_cat);
$this->db->where('expiry_date >', date("Y-m-d"));
$this->db->order_by('id', 'DESC');
$query = $this->db->get('ad_post');
return $query->result_array();
//echo $this->db->last_query();
}
//ajax
<script type="text/javascript">
$(document).ready(function () {
$('#state_id').change(function () {
var selState = $(this).val();
alert(selState);
console.log(selState);
$.ajax({
url: "pages/get_cities",
async: false,
type: "POST",
data : "state="+selState,
dataType: "html",
success: function(data) {
$('#city').html(data);
$("#location_id").html("<option value=''>--Select location--</option>");
}
})
});
});
</script>
Please help me how to solve this issue. Please check the url I have provided and try to select a state from the filter section the problem will be more clear.
In .js what is the value of selState ?
In your model, you should if() else() instead of just a if, because your query will get override.
Where is the get_cities function ? Can we see it ?
On your url, the problem is that your ajax url doesn't return a real ajax call but an entire HTML page which is "harder" to work with. Try to change it into json (for dataType's ajax()) You should only do in your php something like this :
in your controller :
public function get_cities()
{
$state = $this->input->post('state');
//Do the same for $cat
if (!$state) {
echo json_encode(array('error' => 'no state selected'));
return 0;
}
$get_cities = $this->model_something->getCitiesByStateName($state);
echo json_encode($get_cities);
}
You should definitely send with ajax the $cat info
Related
I did a multiselect input dropdown using select2. However, I dont really sure how to fetch the data that I call from database in the dropdown so that I can view it in datatable. Here are my codes:
Script for input dropdown select2:
$('.ethnicity').select2({
placeholder: 'Select..',
ajax: {
url: '/select2-autocomplete-ajax_ethnicity',
dataType: 'json',
delay: 250,
processResults: function ($ethnicity) {
return {
results: $.map($ethnicity, function (item) {
return {
text: item.Bangsa_updated,
id: item.id,
}
})
};
Controller for input dropdown so it will select the input typed:
public function ethnicity(Request $request)
{
$ethnicity = [];
if($request->has('q')){
$search = $request->q;
$ethnicity = DB::table("user")
->select("id","ethnic")
->where('ethnic','LIKE',"%$search%")
->get();
}
return response()->json($ethnicity);
}
The above code only to select the data from database without fetch data to datatable.
The controller below to catch data into datatable (I used this for simple dropdown, however dont know how to change so it is useful for above input dropdown.
public function fnFilter(Request $request)
{
if(request()->ajax())
{
if(!empty($request->dataGender))
{
$data = DB::table('user')
->select('id', 'Fn', 'Ln')
->where('ethnic', $request->ethnicity)
->get();
}
else
{
$data = DB::table('user')
->select('id', 'Fn', 'Ln', 'Umur', 'Phone', 'Dob','St', 'Country','Zip','Ct','Jantina')
->get();
}
return datatables()->of($data)->make(true);
}
$dataName = DB::table('modified_dpprs')
->select('ethnic','Jantina')
->groupBy('ethnic')
->orderBy('ethnic', 'ASC')
->get();
return response()->json($dataName);
Blade is:
<select id="ethnicity" class=" ethnicity form-control select2-allow-clear" style="width:200px;" name="namaDUN" multiple >
<option value="">Select</option>
My idea is to put the result from controller function ethnicity into function fnFilters. But I dont know how can do it.
you can return response in select2 (controller function) required format
like
$final_array = [];
$ethnicity = DB::table("user")
->select("id","ethnic");
if ($request->search != '') {
$search = $request->search ;
$ethnicity=$ethnicity->where('ethnic','LIKE',"%$search%");
}
// loop the results to make response
foreach($ethnicity->get() as $key => $value):
$final_array[$key]['id'] = $value->id;
$final_array[$key]['text'] = $value->ethnic;
endforeach;
return ['results' => $final_array];
// function ends here
and select 2 tag in blade file like this
$('.ethnicity').select2({
placeholder: 'Select..',
ajax: {
url: '/select2-autocomplete-ajax_ethnicity',
minimumInputLength: 3,
data: function (params) {
var query = {
search: params.term,
page: params.page || 1
}
return query;
}
}
});
I am trying to process POST data from ajax to laravel controllers but I can't access it. Here is what I am doing in AJAX.
$.ajax({
type:'POST',
url:'/complete_ca_fin',
data: {fin_id: id},
success:function(data){
console.log(data);
$('#modal_complete').modal('hide');
$('html, body').animate({
scrollTop: 0 }, "slow");
$('#message_form').empty().css('display','block').removeClass('alert-danger').addClass('alert-success').text('Finished Good CA has been successfully completed.');
$('#message_form').fadeOut(4000);
setTimeout(function(){
window.location = '/quality_control';
}, 3000);
refresh_check = true;
window.onbeforeunload = null;
},
error: function (data) {
console.log('Error: ' + data);
} // end of error
}); // ajax
id should be accessed in the controller. Here is my route
Route::post('/complete_ca_fin', 'DatasheetController#complete_ca_fin');
And here is my controller
public function complete_ca_fin(Request $request) {
$id = $request->id;
$complete_ca = FinishedCA::findOrFail($id);
if ($complete_ca){
$complete_ca->status = '5';
$complete_ca->save();
return 'success';
}
//return 'success';
}
When I try to return $id just to test I noticed that it is empty ( I don't if it has anything to do with it ) but I know that var id in the ajax has a value because I tested it in the console.
Here is a sample of the console log. 37 is the value of the id so there should be a value in the controller
You are using findOrfail which means it will throw a 404 if there is no email, you want to be validating if it exists, not 404'ing of not
public function complete_ca_fin(Request $request) {
$id = $request->id;
$complete_ca = FinishedCA::find($id);
if ($complete_ca->exists()){
$complete_ca->status = '5';
$complete_ca->save();
return 'success';
}
//return 'success';
}
Use Input::get('id'); instead of request , So your method will like this
public function complete_ca_fin(Request $request) {
$id = Input::get('id');
$complete_ca = FinishedCA::findOrFail($id);
if ($complete_ca){
$complete_ca->status = '5';
$complete_ca->save();
return 'success';
}
//return 'success';
}
This is the ajax function in the view
<script type="text/javascript">
$('#name').on('change',function(){
var uid = document.getElementById('name').value;
$.ajax({
url : '<?php echo base_url('index.php/Manager_Settings_Controller/getUsername');?>',
method : 'get',
data : {'uid' : uid },
success : function(result){
console.log(result);
}
});
});
This is the getUsername function from the controller
public function getUsername(){
$uid = $this->input->get('uid');
$this->load->model('Manager_Settings_Model');
$data = $this->Manager_Settings_Model->getUsername($uid);
return $data['username'];
}
And this is the model function
function getUsername($uid){
$this->db->select('username');
$query = $this->db->get_where('user',array('u_id'=>$uid));
foreach($query -> result() as $row){
$data = array(
'username' => $row->username,
);
}
return $data;
}
Its really great if someone can help me. Thanks inadvance
public function getUsername(){
$uid = $this->input->get('uid');
$this->load->model('Manager_Settings_Model');
$data = $this->Manager_Settings_Model->getUsername($uid);
echo $data['username'];
}
You got to echo not return in controller, so you get the error or result whatever in console.log in success function of ajax.
I want to show tick.png image on clicking save button when data inserted in database successfully. My view file name is insert_your_committee, model is users_model & controller user
Here is my code of all there files:
My Script of my insert_your_commitee file, All console.log show correct result but success function is not working. What is the problem?
<script>
function save_committee($c_id,$m_id,$start_date){
console.log($c_id);
console.log($m_id);
console.log($start_date);
var mid=$('#irnum'+$start_date).val();
console.log("df"+mid);
var url= "<?php echo site_url("user").'/ref_add';?>";
$.ajax({
url: url,
type: "POST",
dataType:'json',
data: {c_id:$c_id,m_id:$m_id,start_date:$start_date,irnum:mid},
success: function(data){
console.log(data);
$('#'+$start_date).show();
$('#btn'+$start_date).hide();
}
});
}
</script>
My Controller
public function ref_add()
{
$this->load->model('Users_model');
$parms=$this->input->post();
$c_id=$this->input->post('c_id');
$m_id=$this->input->post('m_id');
$s_dateparms=$this->input->post('start_date');
$irnum=$this->input->post('irnum');
$data_to_store = array(
'Cid' =>$c_id,
'Mid' =>$m_id,
'Month' => $s_dateparms,
'Year'=>$s_dateparms,
'Ref_Number' =>$irnum,
);
$params=array();
if ($this->users_model->add_ref($data_to_store)) {
$params['status'] = TRUE;
} else {
$params['status'] = false;
}
$return["json"] = json_encode($params);
echo json_encode($return);
}
And Here is my model
function add_ref($data)
{
$this->db->insert('reference', $data);
$report = array();
$report['error'] = $this->db->_error_number();
$report['message'] = $this->db->_error_message();
if($report !== 0){
return true;
}else{
return false;
}
}
I am not completely sure, but in order to get ajax to work, I had to add return false; after the ajax call in the function.
In my case, I was using ajax for login and backend was in codeigniter.
this is the method I want to send data to it
function get_lesson($reshte,$poodeman){
$this->load->model('dropdown_model');
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($this->dropdown_model->get_lessons($reshte,$poodeman)));
}
and this is the get_lessens() function in the model file.
function get_lessons($reshte = null, $poodeman=NULL){
$this->db->select('rlessid, title');
if($reshte != NULL AND $poodeman!= NULL ){
$this->db->where('reshteid', $reshte);
$this->db->where('poodemanid', $poodeman);
}
$query = $this->db->get('tbllessons_root');
$lessons = array();
if($query->result()){
foreach ($query->result() as $lesson) {
$lessons[$lesson->rlessid] = $lesson->title;
}
return $lessons;
}else{
return FALSE;
}
}
and this is my ajax call at the view file
var reshteid = $('#reshte').val();
var poodemanid = $('#poodemanha').val();
$.ajax({
type:"POST",
url:"http://localhost/crud-grocery/index.php/examples/get_lesson/",//+reshte+"/"+poodeman,
data: "reshte="+reshteid+"&poodeman="+poodemanid,
success: function(lessons)
{
$.each(lessons,function(rlessid,title){
var opt = $('<option />');
opt.val(rlessid);
opt.text(title);
$('#lessons').append(opt);
});
}
});
as you see I am trying to chain options in the form
but The problem comes up when I try to post (send) two parameters to the controller method
any idea?
In your controller, you need to get POST values not as parameters:
//in controller
function get_lessons(){
...
//get POST values
$reshte = $this->input->post('reshte');
$poodeman = $this->input->post('poodeman');
You have to pass data as a javascript object literal:
...
data: {
reshte: reshteid,
poodeman: poodemanid
}
....