Passing Json array value from codeigniter to Jquery calendar Error - php

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.

Related

Ajax request in MVC doesn't return corresponding value to the HTML page

Below is my script in Dashboard module.
$(function()
{
var o;
$.get('dashboard/xhrgetInsert',function(o)
{
for(var i = 0;i <= o.length; i++)
{
$("#appendHere").append("<div>"+o[i].text+"</div>");
}
},'json');
$("#randomInsert").submit(function()
{
alert("hi");
var data = $(this).serialize();
var url = $(this).attr("action");
$.post(url,data,function(o)
{
$("#appendHere").append("<div>"+o+"</div>");
},'json');
return false;
});
});
Supposedly, when I'm in the dashboard page this function(xhrgetInsert) has to return value to be appended in the HTML. Unfortunately, it doesn't append anything and as I checked in the chrome console 'response'..it says method doesn't exist. But If I type the method name in the url, it shows the values returned in json format as I specified so.
Same goes for 'xhrInsert()' function as it doesn't return value to be appended. Database connection is perfect as it can insert and select data from db just unable get back the values..
I'm wondering first, why it says the method doesn't exist, and secondly why doesn't return any value?
My 'Dasboard controller making call to dashboard model'
public function xhrInsert()
{
$this->model->xhrInsert();
}
public function xhrgetInsert()
{
$this->model->xhrgetInsert();
}
Dashboard model contains mysql queries to the database whcih return values in jason format
public function xhrInsert()
{
$text = $_POST['text'];
$sql = $this->db->prepare("INSERT INTO data(text)VALUES(:text)");
$sql->execute(array(':text'=>$text));
echo json_encode($text);
}
public function xhrgetInsert()
{
$sth = $this->db->prepare("SELECT * FROM data");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$data = $sth->fetchAll();
echo json_encode($data);
}
Finally, this is my HTML for dashboard
<h1>Dashboard</h1>
<form id="randomInsert" action="<?php echo URL;?>dashboard/xhrInsert" method="post">
<label>Text: </label><input type="text" name="text"/><br/>
<input type="submit"/>
</form>
<div id="appendHere"></div>
Console Screenshot
Function should return the result json data to ajax request so it won't render the whole html page with result.
public function xhrInsert(){
echo $this->model->xhrInsert();
die;
}
public function xhrgetInsert()
{
echo $this->model->xhrgetInsert();
die;
}
Model
public function xhrInsert()
{
$text = $_POST['text'];
$sql = $this->db->prepare("INSERT INTO data(text)VALUES(:text)");
$sql->execute(array(':text'=>$text));
return json_encode($text);
}
public function xhrgetInsert()
{
$sth = $this->db->prepare("SELECT * FROM data");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$data = $sth->fetchAll();
return json_encode($data);
}

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)

Variables to DB and back codeigniter with jQuery

Ok, so I have a table that looks like this:
echo "<table id='tbl'>";
foreach ($questions as $q1)
{
if($q1->parinte==0)
{
echo "<tr class=".clickable">";
echo "<td class='parrent".$q1->parinte."' id='".$q1->id."'>".$q1->text."</td>";
echo "</tr>";
}
}
The questions variable is passed from my controller and used here.
What I want is when i click a row in that table, I want to check the id of that row with something from my database and then rewrite the table with other rows from my database.
I think it's simplier in jQuery but I kinda new to jQuery and Codeigniter.
Can someone give me an example on how to send the ID when I click a row and compare to something in my database?
Thanks.
LE:
My model:
class Support_help_model extends CI_Model
{
public function get_questions()
{
//Intrebari principale
$query = $this -> db -> query("SELECT * FROM decision_tree");
return $query->result();
}
}
My controller:
class Support_help_controller extends CI_Controller
{
public function index()
{
$this->load->model("support_help_model");
$data['questions'] = $this->support_help_model->get_questions();
$this->load->view('welcome_message', $data);
}
}
onClick of the row, send the variable to your php script (save.php) using ajax. Just like this-
$(".parrent0").click(function() {
$.post( "save.php", { param: this.id }, function( data ) {
alert(data); // here you'll get the db rows returned
});
});
Receiving the variable and returning the result back; save.php-
$param = $_POST['param'];
//
// db queries
//
$db_data; // data/rows to be returned back
echo json_encode($db_data);

jquery posting to php file

Trying to get some jquery code to post a value to a php file I have, and return an array of data.
The basic idea is to search a database, then fill bootstrap's typeahead with the value. Working in CodeIgniter.
Search controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Search extends CI_Controller {
public function index()
{
}
public function getSearchResults()
{
$partialSearch = $_POST['partialSearch'];
if (strlen($partialSearch) > 5) {
$this->db->select('mobile_number');
$this->db->like('mobile_number', $partialSearch);
$query = $this->db->get('phone_lines');
$result = $query->result();
$data = "";
foreach($result as $row){
$data = $data . "<div>" . $row->mobile_number . "</div>";
}
echo $data;
}
}
}
jquery that currently fills the typeahead:
<script>
//searches the database for mobile numbers
$(function() {
var searchItem = $("#typeahead").val();
var itemsArray = [
"1111111111",
"2222222222",
"3333333333"
];
//push to search controller, receive back array of mobile numbers that match
$("#typeahead").typeahead({
source: itemsArray
});
});
</script>
So, I'm not sure how to post the value of the search box to the php, then how to format it properly when it is returned. Any thoughts? Pretty new to all of this. Not even sure it is possible. Any help is much appreciated.
$.ajax, $.post and $.getjson are some of the many jQuery functions out there.

Jquery json request and Kohana

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));

Categories