Jquery json request and Kohana - php

I am trying to learn a little bit of jquery and more about the kohana framework. Ok so I wrote a simple test script to grab some entries from a database. The php works as in it returns the row in a json format, but I guess my jquery isn't working.
The json is suppose to return multiple rows so I want it to add all of those into the #chats div.
Here is my jquery code:
$(document).ready(function() {
$.getJSON('json/get_chat_entries/1',
function(data) {
$('#chats').append('<li>' + data.text + '</li>');
}
});
});
The get entries code is suppose to grab all the entries in the database matching the chat_id. Write now it seems to be only returning the first entry.
here is my get entries code:
function get_entries() {
$entries = $result = DB::select() - > from('chat_entries') - > where('chat_id', '=', $this - > chat_id) - > execute() - > current();
return $entries;
}
And this is the controller code:
public function action_get_chat_entries(){
$chat_id = $this->request->param('id');
$chat = new Model_Chat($chat_id);
echo json_encode($chat->get_entries());
}

Just remove ->current() from your get_entries() method.

Cleaned up a bit:
Model:
public function get_entries()
{
if (!$this->_loaded)
return array();
return DB::select()
->from('chat_entries')
->where('chat_id', '=', $this->chat_id)
->execute($this->_db);
}
Controller:
public function action_get_chat_entries()
{
$id = $this->request->param('id', FALSE);
$chat = new Model_Chat($id);
$this->request->headers['Content-Type'] = 'application/json';
$this->request->response = json_encode($chat->get_entries());
}

$results = DB::select(...)->from(...)->where(...)->execute();
echo json_encode(iterator_to_array($results));

Related

laravel chunk (help)

when i using postman get the result from chunk,but the result will return empty,how can i solve this?
enter image description here
here's my code
public function downloadMemberInfo()
{
error_log('download');
set_time_limit(240); //testing
$memberListsArray = array();
Member::select('vipcode')->where('vipcode','!=','')
->chunk(3000,function($members) use($memberListsArray){
foreach($members as $member){
$memberListsArray[] = $member;
}
});
return response()->json($memberListsArray);
}
You need to call get before use chunk; because chunk works with collections. Try with the next code.
public function downloadMemberInfo()
{
error_log('download');
set_time_limit(240);
$members = Member::select('vipcode')
->where('vipcode', '!=', '')
->get()
->chunk(3000)
->toArray();
return response()->json($members);
}
By the way, I recommend you to use paginate or some query limit to avoid performance issues

AJAX Send array as response from Laravel

I am trying to send from Laravel a response to an AJAX post request.
public function infoRoute(Request $request)
{
// Get info
$ship_id = $request->ship_id;
$startDate = $request->datepicker_start;
$endDate = $request->datepicker_end;
// Get all the locations between those dates
$routeArray = $this->measurementRepository->getCoordinates($ship_id, $startDate, $endDate);
$ship = $this->shipRepository->getShipForId($ship_id);
$info = $this->createRouteArrayForShip($ship, $routeArray);
if($request->ajax()) {
return response()->json(json_encode($info));
}
}
protected function createRouteArrayForShip($ship, $routeArray)
{
$info['type'] = "showRoute";
$index = 0;
foreach($routeArray as $coordinates)
{
$info['info']['route']['loc'. $index] = $coordinates;
$index++;
}
$info['info']['shipInfo'] = $ship;
//dd($info);
return $info;
}
When I receive the information and process it with jQuery, everything shows except from the route, that is empty.
Thank you,
The response()->json() method converts the given array into JSON using the json_encode() PHP function behind the scene.
Therefor you should remove your json_encode() from inside the response()->json() call.
Basically it should look like this
return response()->json($info);

how to display data from database using $.post

hey iam trying to take data from data base using $.post. Here iam taking db data as json ecoded. But i couldn't display or alert the data. If possible how can i display the json array? how can i check the database values in json format? pls help me. iam using codeigniter
function profile_view(id3)
{
$.post("<? echo base_url();?>Attendance/Prev_leave_record", {id:id3},function(data){
//do something
});
}
controller
function Prev_leave_record()
{
$teacher_id=$this->input->post('id');
$teacher_details=$this->AM->prev_record($teacher_id);
$out=array(
'teacher_details'=>$teacher_details);
// echo '{"teacher_details":'.json_encode($teacher_details).'}';
echo json_encode($out);
}
model
function prev_record($teacher_id)
{
$this->db->select('leave_from_date,leave_to_date');
$this->db->from('leave_data');
$this->db->where('applied_user_id',$teacher_id);
$teacher_details=$this->db->get();
return $teacher_details;
}
Try this
Model:
Your model made a query but didn't return the result of the query.
See Returning Query Results.
function prev_record($teacher_id)
{
//This is opinion, but it will be much more efficient
//not using Query Builder for such a simple query
$sql = "SELECT leave_from_date, leave_to_date FROM leave_data WHERE applied_user_id = ?";
$query = $this->db->query($sql, [$teacher_id]);
//always check that the query produced results
//the next statement returns one row as an array or
//returns NULL if the query produced no results
return $query->num_rows() > 0 ? $query->row_array(): NULL;
}
Controller:
function Prev_leave_record()
{
$teacher_id = $this->input->post('id');
$teacher_details = $this->AM->prev_record($teacher_id);
if(isset($teacher_details))
{
$out['results'] = "Success";
$out['teacher_details'] = $teacher_details;
}
else
{
$out['results'] = "Failed";
}
echo json_encode($out);
}
javascript:
function profile_view(id3)
{
$.post("<? echo base_url();?>attendance/prev_leave_record", {id:id3},
function(data)
{
console.log(data); //so you can see the structure returned
if(data.results === "Success){
alert("Cool, it worked: " + data.teacher_details);
} else {
alert("Opps, we didn't get anything.");
}
}
);
}
Try this,
function profile_view(id3)
{
$.post("<? echo base_url();?>Attendance/Prev_leave_record", {id:id3},function(data){
console.log(data); // or alert(data);
});
}
Then check the console from Inspect element from browser (F12 or ctrl+shift+i)

Passing Json array value from codeigniter to Jquery calendar Error

I am trying to integrate Jquery calendar plugin with the codeigniter database and passing Json array what would be the mistake appreciate your help.
calendar.php in view
<script>
var unavailableDates = '<?php echo base_url() ?>Calr/getevent';
$('#calendar').availabilityCalendar(unavailableDates);
</script>
Controller Calr.php
public function getevent()
{
$this->load->model(user/Calr_model/SelectAll);
}
Model Calr_model.php
function SelectAll()
{
$sql = 'SELECT start_date,end_date,link FROM tbl_events';
$query = $this->db->query($sql);
// Fetch the result array from the result object and return it
return $query->result();
}
have tried this function also in calr_model.php
function SelectAll()
{
$sql = 'SELECT start_date,end_date,link FROM tbl_events';
$query = $this->db->query($sql);
// Fetch the result array from the result object and return it
return $query->result();
$emparray = array();
while($row =mysqli_fetch_assoc($query))
{
$emparray[] = $row;
}
echo json_encode($emparray);
}
but json array values is not retrived from database,
static input for which is working in view like
calendar.php
<script>
var unavailableDates = [{start: '2015-08-31', end: '2015-09-05', title:'Event 1'} {start: '2015-09-11', end: '2015-09-15', title:'Event 2'},{start: '2015-09-15', end: '2015-09-23', title:'Event 3'},{start: '2015-10-01', end: '2015-10-07', title:'Event 4'}];
$('#calendar').availabilityCalendar(unavailableDates);
</script>
Regards,
Vinoth
You should have a better distinction between the model and the controller. A model should never echo anything. This is the job of the controller.
Your controller:
public function getevent()
{
$this->load->model('Calr_model');
$data = $this->Calr_model->SelectAll();
echo json_encode($data);
}
Your model (be sure to rename the fields to the proper javascript names, saves you the trouble later):
function SelectAll()
{
$sql = 'SELECT `start_date` AS `start`, `end_date` AS `end`, `link AS `title` FROM tbl_events';
$query = $this->db->query($sql);
return $query->result();
}
You could load this model-method on page load of the normal page. So you don't need another controller for this. If you use AJAX to retreive the data with a normal Ajax call and on success add the events to the calendar with
$.ajax({url: "/Calr/getevent/", success: function(result){
$('#calendar').availabilityCalendar(result);
}});
Mind you, usually the calendar has an event when the calendar is done loading. Use that event to retreive the data via the Ajax function above, otherwise it may not work properly.

codeigniter jquery's autocomplete not working but no error

I'm new to javascript and I tried to follow this tutorial.
I have a textbox(input) and I want to use the jQuery's autocomplete by loading some data from MySQL.
This is my controller code :
public function autocomplete() {
if($this->input->post('txt_nama'))
$this->absensi_m->get_umat($this->input->post('txt_nama'));
/*if (isset($_GET['term'])){
$q = strtolower($_GET['term']);
$this->absensi_m->get_umat($q);
}*/
}
This is my model :
public function get_umat($word) {
$this->db->select('nama', 'tanggal_lahir');
$this->db->like('nama', $word);
$query = $this->db->get('msumat');
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$new_row['label'] = htmlentities(stripslashes($row['nama']));
$new_row['value'] = htmlentities(stripslashes($row['tanggal_lahir']));
//build array
$row_set[] = $new_row;
}
echo json_encode($row_set);
}
}
And this is my javascript :
<script type="text/javascript">
$(function(){
$("#txt_nama").autocomplete({
source: "autocomplete"
});
});
</script>
I tried to inspect the javascript by using firefox's firebug and GC's developer tool, and this is what i got :
<input type="text" id="txt_nama" name="txt_nama" class="ui-autocomplete-input" autocomplete="off">
Notice that the autocomplete is off. I guess this is the problem so i tried to turn it on by adding this code :
$(document).ready(function() {
$("#txt_nama").attr("autocomplete", "on");
});
The autocomplete element is turned on when i add this code, but the autocomplete is still not working.
I also tried to use echo, but none of my echo is working :
if($query->num_rows() > 0)
{
echo num_rows();
echo 'a';
foreach($query->result_array() as $row)
{
$new_row['label'] = htmlentities(stripslashes($row['nama']));
$new_row['value'] = htmlentities(stripslashes($row['tanggal_lahir']));
//build array
$row_set[] = $new_row;
}
echo json_encode($row_set);
//return row_set;
}
What am I missing?
NOTE :
I just wondering about Routes, is it related to this error?because normally, people use controller/method in source: (JavaScript), but I can't do that because the generated route will have double controller (index.php/absensi/absensi/autocomplete), so I remove the controller and just use the method (source: "absensi")
I believe you're using the source option incorrectly. From the docs:
When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data.
If you meant to have source pointing to your autocomplete function, you need to give your controller name like they have on the demo you linked:
source: "birds/get_birds" // path to the get_birds method
Model
public function get_umat($word) {
$this->db->select('nama', 'tanggal_lahir');
$this->db->like('nama', $word);
$query = $this->db->get('msumat');
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$new_row['label'] = htmlentities(stripslashes($row['nama']));
$new_row['value'] = htmlentities(stripslashes($row['tanggal_lahir']));
//build array
$row_set[] = $new_row;
}
return $row_set;
}
}
Controller:
public function autocomplete() {
if($this->input->post('txt_nama'))
echo json_encode($this->absensi_m->get_umat($this->input->post('txt_nama')));
}
You should place echo json_encode() in autocomplete() but not in model..
This is the answer :
DONT use echo, it will break the jquery.
Use if (isset($_GET['term'])) instead of $this->input->post()
Use source: "<?php echo site_url('absensi/autocomplete'); ?>" in the jquery

Categories