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.
Related
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.
I have this application where I use Codeigniter as backend and Backbone as frontend. Now I use the RESTful API from https://github.com/philsturgeon/codeigniter-restserver. I want to fetch RSS feeds, so I created a RSS-model.php in application->models:
<?php
class Rss_model extends CI_Model
{
var $table_name = 'artist_news';
var $primary_key = 'news_id';
function get_all_rss_feeds()
{
$this->db->select($this->primary_key);
$this->db->from($this->table_name);
return $this->db->get();
}
}
?>
and then in application->controllers I created the folder api in which I created the file rss.php:
<?php
require(APPPATH.'libraries/REST_Controller.php');
class rss extends REST_Controller{
public function get_all_rss_feeds_get()
{
$this->load->database();
$this->load->model('rss_model');
$data = $this->rss_model->get_all_rss_feeds();
if($data) {
$this->response($data, 200);
} else {
$this->response(array('error' => 'Couldn\'t find any news!'), 404);
}
}
}
?>
So far so good, it returns an array of text with a lot of rss-feeds, but NOT in JSON format, which I need for my frontend.
Does anyone know what the issue is here?
Thanks in advance...
[EDIT]
My Backbone Code looks like this:
function (App, Backbone) {
var Rss = App.module();
Rss.View = Backbone.View.extend({
template: 'rss',
initialize: function() {
this.listenTo(this.collection, 'all', this.render)
},
serialize: function() {
return this.collection ? this.collection.toJSON() : [];
}
});
Rss.RssCollection = Backbone.Collection.extend({
url: function() {
return '/myproject/index.php/api/rss/get_all_rss_feeds/';
}
});
return Rss;
}
go to config/rest.php file and find this line :
$config['rest_default_format'] = 'xml';
change it to :
$config['rest_default_format'] = 'json';
I think you missed the result in return in the model please check below
function get_all_rss_feeds()
{
$this->db->select($this->primary_key);
$this->db->from($this->table_name);
return $this->db->get()->result();
}
If you are usign the Phil Sturgeon REST library you need to append the format type in the URL. Example:
http://example.com/books.json
http://example.com/books?format=json
If you want it in another format, let's say XML, you just need to pass the new format in the URI, doesn't need to change anything in your code. Example:
http://example.com/books.xml
http://example.com/books?format=xml
Further reading:
Content-Type Section - https://github.com/philsturgeon/codeigniter-restserver
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);
I want to perform CRUD operations through REST, I am implementing this in codeigniter, The code whatever I pasted here is working, but I have to handle a way to fetch all the datas from the database and also a way to fetch the data by id. Is there any best way to do this?
Backbone.js
(function(){
Backbone.emulateHTTP = true;
//Backbone.emulateJSON = true;
window.App = {
Models: {},
Collections: {},
Views: {},
Router: {}
};
App.Models.Task = Backbone.Model.extend({
defaults: {
title: '',
done: 0
},
urlRoot: 'index.php/taskController/task'
});
})();
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require(APPPATH.'libraries/REST_Controller.php');
class taskController extends REST_Controller {
public function task_get($id){
$this->load->model('Task', 'task');
$data['task'] = $this->task->findbyid($id);
}
public function tasks_get(){
$this->load->model('Task','task');
$data['task'] = $this->task->find();
$this->response($data,200);
}
public function task_put($id)
{
# code...
$this->load->model('Task', 'task');
$data = json_decode(file_get_contents('php://input'), true);
// $data['title'] = $var['title'];
// $data['done'] = $var['done'];
echo var_dump($data);
$data['task'] = $this->task->updatebyid($id,$data);
//$this->response($data,200);
}
public function task_delete($id){
$this->load->model('Task','task');
$data['task'] = $this->task->delete($id);
}
public function task_post(){
$this->load->model('Task','task');
$data = json_decode(file_get_contents('php://input'),true);
return $data['task'] = $this->task->create($data);
}
}
I use /get/id for the items and /list/number_to_show/limit
So add a list_get($number, $limit)
method
if code for a /get/id is no id is passed, Send the entire lot ?
The principle of REST is that the CRUD actions are represented by the HTTP verbs. GET = select, PUT = update, POST = create and DELETE = delete.
You use nouns in your URL to represent your resources (e.g. tasks).
From your CI code it looks like you use always GET and have verbs+nouns in your URLs.
In REST, to get all tasks you would need to do GET http://example.com/tasks. To get one specific task you would need to do GET http://example.com/tasks/1234
Please read http://info.apigee.com/Portals/62317/docs/web%20api.pdf to understand the principle.
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