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
Related
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)
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.
When i post the data from the other form , and when i test it in print($id)it works, but when i pass it in the view, when the view loads , it returns as null.
Here is my code :
Jquery post
function viewAccount(orId)
{
account_id=orId;
// alert(account_id);
var postData={
"id":account_id
};
$.post(base_url+"admin/viewAccount", postData).done(function(data){
inlcudeViews('admin/viewAccount');
});
}
Controller:
function viewAccount()
{
$id = $this->input->post('id');
$data = array('id' => $id);
// print_r($data); IT WORKS TILL HERE
$this->load->view('admin/viewAccount', $data);
}
View:
// HERE IS WHERE I GET A NULL VARIABLE
var data='<?= $id ?>';
$(document).ready(function() {
alert(data);
});
Instead of using alert in viewAccount view you just need to print or echo your $id like,
<?php
echo isset($id) ? $id : '';
?>
Also, verify you have already enable PHP short tags in php.ini. If your are using <?= $id ?>
Your Jquery and View is perfect. But in Controller you have to write
$this->load->view('admin/viewAccount', $data[0]);
instead of
$this->load->view('admin/viewAccount', $data);
or you can write
function viewAccount()
{
$id = $this->input->post('id');
$data['id'] =$id;
// print_r($data); IT WORKS TILL HERE
$this->load->view('admin/viewAccount', $data);
}
You need to pass your id into data array like below
Controller
$id = $this->input->post('id');
$data['id']=$id;
//print_r($data); IT WORKS TILL HERE
$this->load->view('admin/viewAccount', $data);
You have not echo $id in your javascript this should be like echo $id:
Update here :
// HERE IS WHERE I GET A NULL VARIABLE
var data='<?php echo $id; ?>';
$(document).ready(function() {
alert(data);
});
thanks for the fast responses, noone of the answers above work.
I managed to find a solution , but its completely different method i just put id as a global variable.
But i would be still interested in the answer of this, i assume it will help other people to
I Need help on how can i get values of second select box based on first select box
This is view:
$(document).ready(function() {
$('#state').change(function() {
// Get an instance of the select, and it's value.
var state = $(this),
stateID = state.val();
// Add if statement to check if the new state id
// is different to the last to prevent loading the same
// data again.
// Do the Ajax request.
$.ajax({
url : 'http://localhost/ci_ajax/select/get_cities/'+stateID, // Where to.
dataType : 'json', // Return type.
success : function(data) { // Success :)
// Ensure we have data first.
if(data && data.Cities) {
// Remove all existing options first.
state.find('option').remove();
// Loop through each city in the returned array.
for(var i = 0; i <= data.Cities.length; i++) {
// Add the city option.
state.append($('option').attr({
value : data.Cities[i].value
}).text(data.Cities[i].city));
}
}
},
error : function() {
// Do something when an error happens?
}
});
});
});
<form action="" method="post">
<select name="state" id="state">
<option>Select</option>
<?php foreach($states as $row):?>
<option value="<?php echo $row->id?>"><?php echo $row->states;?></option>
<?php endforeach;?>
</select>
<select id="cities" name="cities">
<option>Select</option>
</select>
This is controller:
class Select extends CI_Controller{
function index(){
$data['states']=$this->load_state();
$this->load->view('form',$data);
}
function load_state(){
$this->load->model('data_model');
$data['states']=$this->data_model->getall_states();
return $data['states'];
}
function get_cities() {
// Load your model.
$this->load->model('data_model');
// Get the data.
$cities = $this->data_model->get_cities();
// Specify that we're returning JSON.
header('content-type: application/json');
// Return a JSON string with the cities in.
return json_encode(array('Cities' => $cities));
}
}
This is model:
class Data_model extends CI_Model{
function getall_states(){
$query=$this->db->get('states');
if($query->num_rows()>0){
foreach($query->result() as $row){
$data[]=$row;
}
return $data;
}
}
function get_cities(){
$this->db->select('id,cities');
$this->db->from('cities');
$this->db->where('s_id',$this->uri->segment(3));
$query=$this->db->get();
if($query->num_rows()>0){
foreach($query->result() as $row){
$data[]=$row;
}
return $data;
}
}
}
Please help on this hopefully provide the correct code.
Because you are accessing the get_cities() function directly, rather than from another function in the controller, your return statement will not actually print the json array to the page.
return json_encode(array('Cities' => $cities));
There are 3 ways to print it: the first is to print or echo the json array (bad practice), the second is to use a view that prints the raw text sent to it. I.E.
$this->load->view('raw', array('data' => json_encode(array('Cities' => $cities)));
With raw.php being just:
<?php print $data; ?>
Or finally you can use the set_output() function in the output class like this:
$this->output->set_output(array('data' => json_encode(array('Cities' => $cities)));
You may also want to make your function load_state() private if it is only going to be accessed from the index() function.
You may have other problems with your code but that is the most obvious one.
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));