How to post multiple data through $.ajax to Codeigniter controller method - ajax

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

Related

AJAX POST to laravel returning 404 not found

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

Ajax response Not working in Codeigniter

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.

retriev data from controller using ajax

below code returns me blank in ajax response please help me
when i check my controller it also gives me blank.
Can you please check the code below to find out the reason of problem
here is my ajax code:
window.onload = function() {
$.ajax({
type:'json',
url:"http://localhost/myapne/admin/adminMenu/getMsg",
success:function(data){
alert(data);
// PrintSms(data);
},
error: function(error){
console.log(error);
}
});
}
here is my controller:
class AdminMenu extends CI_Controller{
function getMsg(){
$this->load->model('adminGetModel');
$data = $this->adminGetModel->getSms();
return array("status"=>"success","rows"=>$data);
}
}
here is my model:
class AdminGetModel extends CI_Model{
function getSms(){
// $a = $count*10;
// $b = $a + 10;
$this->load->database();
$query = $this->db->get('tblsms');
$rows = array(); //will hold all results
foreach($query->result_array() as $row)
{
$rows[] = $row; //add the fetched result to the result array;
}
return $rows;
}
}
Json_encode the data and use echo instead of return:
echo json_encode(array("status"=>"success","rows"=>$data));
This will return a string. If you want to turn it back into an object, you will then have to use JSON.parse() (or $.parseJSON if you're using jquery) in your ajax success handler.

Ajax changing the entire sql query

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

Sending array to controller/model in CI with AJAX

So basically I have a two item array in javascript that is generated based on which link the user clicks. I am trying to send this array to my controller, and then to the model. The model will look at the array and match one of the items to a certain column/row, and will selectively display data.
I am having issues passing the data from AJAX to my controller.
AJAX code (in a .js file)
$('#youmax-video-list-div').append('<div id="testing1"></div>');
$('#concept').click(function(){
console.log(course);
$.ajax({
url: 'http://localhost:8888/index.php/trial/getValues',
type:'POST',
dataType: 'json',
data:'',
error: function(){
$('#testing1').append('<p>goodbye world</p>');
},
success: function(result) {
var htmlStr = '';
$.each(result, function(a, b){
htmlStr += b.qText + '<br />';
});
$('#testing1').append(htmlStr);
} // End of success function of ajax form
}); // End of ajax call
});
I am assuming I must do something with the data field, but I dont know the syntax for it.
The console log in chrome comes up with this:
Array[2]
0: "PL8G0kdHFfE3WuyevUDvwSYCZw8mp8LBFA"
1: "PL8G0kdHFfE3V62Jp2ju-PelOaNUkH7xR8"
Controller
function getValues(){
$this->load->model('get_db');
$data = $this->get_db->getAll();
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));
return $data;
}
Model
class Get_db extends CI_Model{
function getAll(){
$query=$this->db->query("SELECT * FROM questions");
return $query->result();
//returns from this string in the db, converts it into an array
}
}
As I said before, I am really only concerned with getting the data to my controller and my model.
The name of the array is "course". However, that doesnt appear to be so in the console.log. Is that just something chrome does?
// chkval be the class for elements for the arrays
AJAX function:
function ajaxSub(goals)
{
var theArray = new Array();
var i=0;
jQuery('.chkval').each(function(){
if(jQuery(this).prop('checked'))
{
theArray[i] = jQuery(this).val();
i++;
}
});
jQuery.ajax({
url: '<?php echo site_url('mycontroller/myfunctions');?>',
type: 'post',
data: {
arr: theArray,
other_id: ''
},
datatype: 'json',
success: function () {
}
});
}
in the controller:
$arr = $this->post('arr');
foreach($arr as $ar)
{
echo $ar; // prints each element of the array.
}
Same as above answer but in controller run this code:
$arr = $this->input->post('arr');
foreach($arr as $ar)
{
echo $ar; // prints each element of the array.
}

Resources