Passing a value from Controller to jQuery CodeIgniter - php

Straight to the case.
This is some functions from my model (Student Model):
public function get_exam_data($exam_id){
$this->db->select('exam_id, exam_name, duration');
$this->db->from('exams');
$this->db->where('exam_id', $exam_id);
$result = $this->db->get();
$exam = array();
$examrow = $result->row();
$exam['id'] = $examrow->exam_id;
$exam['name'] = $examrow->exam_name;
$exam['duration'] = $examrow->duration;
return $result;
}
public function start_exam($exam_id, $student_id)
{
$this->db->select('*');
$this->db->from('exam_record');
$exam_newstatus = array(
'student_id' => $student_id,
'exam_id' => $exam_id);
$this->db->set('start_time', 'NOW()', FALSE);
$this->db->insert('exam_record', $exam_newstatus);
//$examrecord_id is autoincrement in mysql exam_record table
$examrecord_id = $this->db->insert_id();
return $examrecord_id;
}
This is a function from the Student Controller:
public function get_student_exam_data()
{
$exam_id = $this->input->post('examId');
$examdata = $this->student_model->get_exam_data($exam_id);
$session = get_session_details();
if (isset($session->studentdetails) && !empty($session->studentdetails))
{
$loggeduser = (object)$session->studentdetails;
$examrecord_id = $this->student_model->start_exam($exam_id, $loggeduser->student_id);
}
echo json_encode($examdata);
}
This is how I access the $examdata value via Ajax:
jQuery(function()
{
$.ajax({
type : "POST",
url : "../get_exam_data/",
async : false,
data : {"examId": EXAM_ID },
success: function(response)
{
var data = $.parseJSON(response);
examId = data.id;
examName = data.name;
examDuration = data.duration;
}
});
}
I want to be able to pass $examrecord_id from the Student Controller to use it on my jQuery file, just like the $examdata.
I tried to use json_encode() twice on the Controller. Didn't work.
How do I pass $examrecord_id from the Controller to the jQuery file?
Can someone enlighten me, please? Thank you.

Add another index for your $examrecord_id
if (isset($session->studentdetails) && !empty($session->studentdetails))
{
$loggeduser = (object)$session->studentdetails;
$examrecord_id = $this->student_model->start_exam($exam_id, $loggeduser->student_id);
}
echo json_encode(array(
'examdata' => $examdata,
'examrecord_id' => (!empty($examrecord_id)?$examrecord_id:0)
));
Note the shorthand if condition to check if $examrecord_id is empty
Add a dataType option with 'json' as it's value. Then you can access the data
dataType : 'json',
success: function(response)
{
var data = response.examdata;
alert(response.examrecord_id); // your examrecord_id
examId = data.id;
examName = data.name;
examDuration = data.duration;
}

Related

Unable to pass array data from view to controller using AJAX

The data (array of array) is not getting passed from view to controller while using AJAX in CodeIgniter (PHP)
url is working in $.ajax. It is redirecting to the method in controller
view.php (view)
$('#save').click(function(){
var table_data = [];
// use .each to get all data
$('#data_table tr').each(function(row,tr){
// create array again to store data by row
// get only data with value
if ($(tr).find('td:eq(0)').text() == "") {
} else {
var sub = {
'no' : $(tr).find('td:eq(0)').text(),
'firstname' : $(tr).find('td:eq(1)').text(),
'middle' : $(tr).find('td:eq(2)').text(),
'last' : $(tr).find('td:eq(3)').text(),
};
table_data.push(sub);
}
});
//use ajax to insert the data
console.log(table_data);
var data = {'data_table':table_data};
console.log(data);
$.ajax({
data : data,
type : 'POST',
url : 'save',
crossOrigin : false,
dataType : 'array',
success: function(msg){
$('.answer').html(msg);
}
});
Welcome.php (controller)
public function save() {
$relatives_list = $this->input->post('data');
echo 'as';
echo $relatives_list;
// the list is not shown here
$this->load->model('Batch');
$status = $this->Batch->save($relatives_list);
$this->output->set_content_type('application/json');
echo json_encode(array('status' => $status));
}
Batch.php (model)
public function save($relative_list){
$length = count($relative_list);
for($x = 0; $x < count($relative_list); $x++){
$data[] = array(
'no' => $relative_list[$x]['no'],
'firstname' => $relative_list[$x]['firstname'],
'middle' => $relative_list[$x]['middle'],
'last' => $relative_list[$x]['last'],
);
}
try {
for($x = 0; $x<count($relative_list); $x++){
$this->db->insert('hhh',$data[$x]);
}
return 'success';
}catch(Exception $e) {
return 'failed';
}
}
Error:
parameter-must-be-an-array-or-an-object-that-implements-countable
According to your script it wouldn't be data it would be data_table
var data = {'data_table':table_data};
Thus:
var_dump($this->input->post('data_table')
If that doesn't work please post the console.log of your data var.
Please note: you will have to remove the echos before json_encode after you are done troubleshooting or jquery will fail to parse the response.

Codeigniter: Ajax data is printing in log but not working in function

I'm getting data through ajax who's function is:
<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
$("#submit").click(function(event)
{
event.preventDefault();
var hiddenValue = $("#hiddenValue").val();
alert(hiddenValue);
var update_name = $("input#update_name").val();
// pop up Name Entered
alert(update_name);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "seasons/update_season",
data: {
hiddenValue : hiddenValue,
update_name: update_name
},
success: function(res)
{
console.log(res);
// window.alert("i got some data ");
if (res)
{
jQuery("div#result").show();
}
},
fail: function(res)
{
console.log(res);
}
});
});
});
The Controller function i have:
public function update_season()
{
$session_id = $this->session->userdata('id');
if (isset($session_id))
{
// print_r($_POST);
// die();
$update_id = $this->input->post('hiddenValue');
$update_name = $this->input->post('update_name');
$arr = array(
'id' => $update_id,
'name'=> $update_name);
//This prints empty data
// print_r($arr);
// die();
$result = $this->model_season->edit_season($arr);
// $result = $result->row();
if ($result)
{
print_r($arr);
}
else
{
return FALSE;
}
}
else
{
redirect('user_authentication');
}
}
And in Model through controller i have:
public function edit_season($data)
{
// I am getting right array of name and id
print_r($data);
die();
// but get empty variable if i try to assign value to it
$name = $data['name'];
$this->db->where('seasons', array('season_id ' => $data['id']));
$query = $this->db->update('seasons',array('names ' => $data['name'] ));
if ($query)
{
return $query;
}
else
{
return FALSE;
}
}
The ajax seem to work fine as its printing the values of id and name its getting i'm not even encoding it in json, but i'm unable to get its value in separate variable. I wonder if there is any different method to get values from ajax data ?
When i let it run the whole model function without making it die i have following error:
UPDATEseasonsSETnames= NULL WHEREseasons=Array``
Like array have nothing in it
There is error in your query, you are supplying array to where condition, where it should be string,
$this->db->where('season_id ', $data['id']);
Also, it is not good to have unnecessary spaces (though CI driver internally trims all spaces) in conditions like 'season_id ' should be 'season_id'
$this->db->where('season_id', $data['id']);
$query = $this->db->update('seasons', array('names' => $data['name']));
Check driver referance here: Queries in CI
$array1= array('season_id ' => $data['id']);
$array2= array('names' => $data['name']);
$this->db->where($array1);
$query = $this->db->update('seasons',$array2);

Call to a member function row() on a non-object when updating a table

I am using codeigniter to develop my app. And I am using jquery to send some json data.
This is my code :
Model :
public function updateRequest($id_request, $jenis_request, $keluhan ){
$data= array(
'jenis_request' => $jenis_request,
'keluhan' => $keluhan
);
$this->db->where('id_request', $id_request);
$query = $this->db->update('tbl_requestfix', $data);
return $query->row();
controller :
public function updateRequest(){
$id = $_POST['id'];
$jenis_request = $_POST['jenis_request'];
$keluhan = $_POST['keluhan'];
$row = $this->model_request->updateRequest($id, $jenis_request, $keluhan );
echo json_encode($row);
}
This is the view using ajax
$('#btn-footer').click(function(e) {
e.preventDefault();
var id = $("#mainTitle strong").text().split("/").pop();
/*get value checkbox*/
var jenis_request = [];//console.log($("input[name='request[]']"));
$("input[name='request[]']:checked").each(function() {
//console.log($(this).val());
jenis_request .push($(this).val());
});
jenis_request = jenis_request.join(',');
alert(jenis_request); //for check
/*ambil keluhan*/
var keluhan = $('#modalkeluhan').val();
$.ajax({
url: '<?php echo base_url() . 'control_closing/updateRequest/' ?>',
type : 'POST',
data : {id : id ,
jenis_request : jenis_request,
keluhan : keluhan
},
dataType: 'json',
success: function (obj) {
console.log(obj);
}
});
});
I got this error, Call to a member function row() on a non-object ,
I know that row() is an object, is that a problem ?
This may help you
public function updateRequest($id_request, $jenis_request, $keluhan )
{
$data= array(
'jenis_request' => $jenis_request,
'keluhan' => $keluhan
);
$this->db->where('id_request', $id_request);
$query = $this->db->update('tbl_requestfix', $data);
$affected_rows=$this->db->affected_rows();
if($affected_rows >0)
{
return $affected_rows." rows updated";//return here the way you want
}
else
{
return "No updates";
}
}

Use AJAX to Filtering Data on the Table with Select Box in Codeigniter

I have an issue when using AJAX to filter data on the table. I have a select box and table on the page. I want to filter data on the table using the select box. example, if the user chooses value 'Ganjil' on the select box then table just show row that has data 'Ganjil'.
AJAX Script:
<script>
var semester = $("#inputJenis").change(function(){
$.ajax({
type:"POST",
url:'<?php echo base_url("search/filter") ?>',
data:"key="+semester,
dataType:'json',
success:function(data){
$("#tableData").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>
Controller:
public function filter()
{
$this->load->helper('url');
$key = $this->input->post('semester');
if ( $key == 'Ganjil' ) {
$this->load->model('filter_model');
$data = $this->filter_model->getGanjil($key);
} else {
$this->load->model('filter_model');
$data = $this->filter_model->getGenap($key);
}
echo json_encode($data);
}
Model:
public function getGanjil($key)
{
$sql = "SELECT * FROM tahunajaran WHERE jenis = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}
public function getGenap($key)
{
$sql = "SELECT * FROM tahunajaran WHERE jenis = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}
When I choose the value of select box table show nothing.
1st Solution : use $key = $this->input->post('key'); in controller as you access key value pair. So in AJAX call $key is Key. You cant access javascript variable semester like $this->input->post('semester'); in your code.
2nd Solution :
in ajax call url:'<?php echo base_url("search/filter/key/") ?>'+semester
Use $key='' as parameter in controller method .
public function filter($key='') as there is no $key accessible in your controller method. You should be accessing in your controller as a parameter. So you can use it in model . In your case there is no $key coming as a parameter in controller.
Also in your code use
$key = $this->input->post($key); as we access $key thru parameter.
-------------Update 1----------
As per your requirement , AJAX call
<script>
var semester = $("#inputJenis").change(function(){
$.ajax({
type:"POST",
url:url:'<?php echo base_url("search/filter/key/") ?>'+semester,
data:"key="+semester,
dataType:'json',
success:function(data){
$("#tableData").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>
And your controller should be like this ->
public function filter($key = '')
{
$this->load->helper('url');
if ( $key == 'Ganjil' ) {
$this->load->model('filter_model');
$data = $this->filter_model->getGanjil($key);
} else {
$this->load->model('filter_model');
$data = $this->filter_model->getGenap($key);
}
echo json_encode($data);
}

CakePHP trying to send a ajax request

I'm trying to send a ajax requistion to a controller, that it should returns something, but isn't.
My element (View/Elements/list.ctp):
<script type="text/javascript">
$(document).ready(function(){
$('#click').click(function(){
$.ajax({
type: "POST",
url: '<?php echo Router::url(array('controller' => 'products', 'action' => 'showProducts')); ?>',
success: function(data){
alert(data);
}
});
});
});
</script>
<p id="click">Click me!</p>
Controller products:
<?php
class ProductsController extends AppController {
public $helpers = array('Js' => array('Jquery'));
public $components = array('RequestHandler');
var $name = 'Products';
function showProducts(){
return 'This should to return in jQuery data';
}
}
?>
In cakePHP 2.x your controller needs to be in this way to return json data to the $.ajax request :
<?php
App::uses('AppController', 'Controller');
App::uses('JsBaseEngineHelper', 'View/Helper');
class AjaxtestsController extends AppController {
function beforeFilter() {
parent::beforeFilter();
}
public function returnsSomthing()
{
$layout = 'ajax'; // you need to have a no html page, only the data.
$this->autoRender = false; // no need to render the page, just plain data.
$data = array();
$jquerycallback = $_POST["callback"];
//do something and then put in $data those things you want to return.
//$data will be transformed to JSON or what you configure on the dataType.
echo JsBaseEngineHelper::object($data,array('prefix' => $jquerycallback.'({"totalResultsCount":'.count($data).',"ajt":','postfix' => '});'));
}
}
Improved Answer
You can use your controller's methods to search data on the db: find(), but I move the search queries to the Model:
First: Add the marked lines at the model code
App::uses('AppModel', 'Model');
App::uses('Sanitize', 'Utility'); // <---
App::uses('JsBaseEngineHelper', 'View/Helper'); // <---
Second: Create a Model method that executes the search:
public function getdata(){
$input = NULL;
$query = array();
$sql = NULL;
$data = array();
$i = 0;
$input = $_GET["name_startsWith"]; // <-- obtains the search parameter
$input = Sanitize::clean($input); // <-- prepares the search parameter
$sql = "select * from atable where condition like '".$input."%';";
$query = $this->query($sql); // <-- the model execute the search
if ($query){
$c = count($query);
for($i=0;$i<$c;$i++){ // <-- iterate over the returned data
$json['id'] = $query[$i][0]['id'];
$json['column1'] = $query[$i][0]['column1'];
$json['column2'] = $query[$i][0]['column2'];
$data[] = $json; // <-- the data it's stored on an multiarray, to be converted to JSON
}
}
$jquerycallback = $_GET["callback"];
echo JsBaseEngineHelper::object($data,array('prefix' => $jquerycallback.'({"totalResultsCount":'.count($query).',"search":','postfix' => '});')); //<-- the data it´s returned as JSON
}
Then: On the controller create a method to call the search
public function getdata()
{
$layout = 'ajax'; //<-- No LAYOUT VERY IMPORTANT!!!!!
$this->autoRender = false; // <-- NO RENDER THIS METHOD HAS NO VIEW VERY IMPORTANT!!!!!
$this->Cliente->getclient(); // <-- Get the data
}
You can call this method via ajax like this:
$.ajax({
url: "/application/controller/getdata",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 10,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.search, function( item ) {
return {
value: item.id,
label: item.column1+" "+item.column2
}
}));
}
});
Check this for more info:
CakePHP Controller:autorender
CakePHP JsonView
Typo Quotes mismatch
Use double quotes to wrap
url: "<?php echo Router::url(array('controller' => 'products', 'action' => 'showProducts')); ?>",
^ ^
Problem
url: '<?php echo Router::url(array('controller' => 'products',
var ^ str^ var
controller and products are treated as variables not strings

Categories