autocomplete get data from database didn't work - html

hye,I want to do the autocomplete for a system. I review a tutorial from here -> [http://cahbagusnongkrong.blogspot.my/2016/11/membuat-autocomplete-dari-database.html.]
the problem is my autocomplete still didn't works eventho I do the same as the tutorial did (just change the name)
so here is my controller:
public function __construct()
{
parent::__construct();
$this->load->model('Kepakaran_m');
$this->load->helper('url', 'form');
}
public function index()
{ $this->load->helper('form');
$autocomp_bidang = $this->Kepakaran_m->get_bidang();
$this->template->set('autocomp_bdg', $autocomp_bidang);
$this->template->set('kepakaran',$kepakaran_staff);
$this->template->render('profil/profilpersonal');
}
public function get_bidang() {
$keyword = $this->uri->segment(3);
$data = $this->dbsmk->from('kexpt103kodbidang')->like('bidang',$keyword)->get();
foreach($data->result() as $row)
{
$arr['query'] = $keyword;
$arr['suggestions'][] = array(
'value' =>$row->bidang
);
}
echo json_encode($arr);
}
and my model is as written below :
function get_bidang(){
$sql= "SELECT bidang FROM kexpt103kodbidang ORDER BY bidang";
$query = $this->dbsmk->query($sql);
return $query->result();}
my view is here :
<div class="col-sm-4 col-sm-offset-1">
<div class="form-group">
<div class="col-md-12">
<input type="text" class="form-control autocomplete" name="bidang" id="bidang" autofocus/>
</div>
</div>
</div>
<script type="text/javascript">
var site = "<?php echo site_url();?>";
$(function(){
$('#bidang').autocomplete({
serviceUrl: site+'expert/get_bidang',
});
});
</script>

You need to debug your functionality. First check is your controller working.
You can try below code :
<script type="text/javascript">
var site = "<?php echo site_url();?>";
$(function(){
$('#bidang').autocomplete({
serviceUrl: site+'expert/get_bidang/'+$(this).val()
});
});
</script>
You need to pass value for keyword. Also try to check using firebug which URL actually being called.
Try to debug by printing results before sending from controller. You can also try with static array from controller.
Let me know if any issue in debugging.

Related

Pull data from SqlServer Database into jQuery Full Calendar using codeigniter3

I am facing same issue from so many days... Previously I worked with same calendar with PHP, but my project is in Codeigniter, so it is not fitted into my project... So now I am working with Codeigniter..
Controller Code
class Calendar extends CI_Controller
{
public function __construct()
{
Parent::__construct();
$this->load->model('Calendar_model');
}
public function index()
{
$this->load->view('Calendar_view');
}
public function load()
{
$query = $this->Calendar_model->load_events();
$data_events = array();
foreach($query->result() as $row)
{
$data_events[] = array(
"title" => $row->title,
"start" => date('Y-m-d H:i:s',strtotime($row->start_event)),
"end" => date('Y-m-d H:i:s',strtotime($row->end_event))
);
}
echo json_encode($data_events);
}
}
Model Code
class Calendar_model extends CI_Model
{
public function __construct()
{
Parent::__construct();
}
public function load_events()
{
$query = $this->db->get("events");
return $query;
}
}
When I run the above with this url http://localhost/calendar_sql_copy/index.php/Calendar/load,
I got following data
[{"title":"Meeting2","start":"2019-09-30 00:00:00","end":"2019-09-30 00:00:00"},{"title":"Meeting2","start":"2019-02-08 00:00:00","end":"2019-03-08 00:00:00"}]
But when I try to pull same data into Fullcalendar in following way..
<script>
$(document).ready(function(){
var calendar = $('#calendar').fullCalendar({
editable:true,
header:{
left:'prev,next today',
center:'title',
right:'month,agendaWeek,agendaDay'
},
selectable:true,
selectHelper:true,
// events:[
// {
// "title":"Meeting2",
// "start":"2019-09-30 00:00:00",
// "end":"2019-09-30 00:00:00"
// }
// ]
events:'<?php echo site_url('Calendar/load'); ?>'
</script>
If I show same data in static way as
events:[
{
"title":"Meeting2",
"start":"2019-09-30 00:00:00",
"end":"2019-09-30 00:00:00"
}
]
It pops up into calendar,
But when I try to render with URL like below,
events:'<?php echo site_url('Calendar/load'); ?>'
Here is the data from the browser Network tool: https://intouchsystems-my.sharepoint.com/:u:/g/personal/gurubaran_k_icsoft_co_in/EZE8m-w3Pn1HoktYxL2yHPQBKcuosFXP1M3uT69bh9qn9Q?e=4%3a5RjKNu&at=9
It does not show even my Calendar....
Where I done mistake please tell me....
It is very important module in my project...
In my organization no WebDevelopers are there, and I am new to this Codeigniter...
Based on the information provided both in the question and the comments, the the reason for the problem is this:
<!-- Calendar.php --> <!-- Calendar_model.php -->
in your AJAX Response. Your response must contain JSON only and nothing else. No other text, no whitespace at the start and end...nothing except the JSON. If you include other data like this then jQuery (and thus fullCalendar) cannot parse the JSON correctly.
Please ensure that the server is not outputting extra data in the response. That will fix the problem.

how to pass the database fetched values from controller to view page using ajax and json

how to pass the database fetched values from controller to view page using ajax and json.i have a controller and model code but i dont know how to pass values from controller to view page
Controller
public function supplier_get_data(){
$query = $this->Profile_model->supplier_communication();
echo json_encode($query);
}
model
public function supplier_communication(){
$sql = $this->db->get('communication');
$sql = $sql->result_array();
return $sql;
}
view page
<div class="left">
<div class="row">
<div class="col-md-1">
<img src="<?php echo base_url(); ?>images/xxxx.jpg" class="img-circle" width="30px" height="30px"/>
</div>
<div class="col-md-11">
<div class="left_msg_block">
<div class="left_messagetext">here i want to display the database values</div>
</div>
</div>
</div>
</div>
This code may helps you
Controller function
public function supplier_get_data(){
$query = $this->Profile_model->supplier_communication();
echo json_encode($query);
}
Model function
public function supplier_communication(){
$sql = $this->db->get('communication');
$sql = $sql->result();
return $sql;
}
Ajax function
function loadData()
{
$.ajax({
type:"post",
url:"<?php echo site_url('controllername/supplier_get_data')?>",
dataType:"json",
success:function(data){
for(i=0;i<data.length;i++){
alert(data[i].columnanme)
$(''+data[i].columnanme+'').appendTo('.left_messagetext');
}
}
});
}

How to pass parameter with $location directive in Anjularjs

I am new to Anjularjs. I tried to pass parameter with $location directive in Angularjs but console says "category not defined". What i am missing. Here is my code:
$scope.editCategory = function(category) {
alert(category.identity);
$scope.resetError();
$scope.category = category;
$scope.catlist=category;
$location.path('categories/edit').search({param:category});
};
I need to pass that category object in categories/edit url.
It is not working. Thanks in advance.
try this.
$location.path('/myURL/').search({param: 'value'});
will result in
`/myURL/?param=value`
OR
$location.path('/myURL/'+ param1);
Please find $location for more details
EDIT CODE 2:
here what I have tried.
HTML :
<div ng-controller="testCtrl">
<a ng-click="setParam()" href="javascript:void(0)">send query param</a> <br>
<a ng-click="getParam()" href="javascript:void(0)">get query param</a>
</div>
JS :
app.controller("testCtrl",function($scope,$location){
var obj = {
id: "331e25d6-fbb5-42a5-b76d-fcac9b30a26e",
trash: false,
identity: "momo",
description: null,
menuItems : [0,12]
}
$scope.setParam = function(){
$location.search({param: obj})
}
$scope.getParam = function(){
console.log($location.search().param);
}
})
otherway :
$scope.getParam = function(){
var arrParam = $location.search().param;
console.log($location.search().param,arrParam);
}

Data-binding MVC-4 to a Knockout.js foreach

We have a form in our web application that, in one place, asks the user to enter a list of values. We wrote this part of the form using Razor and knockout.js so that there is a textbox for each value of the list, similar to this tutorial. How can we data-bind these textboxes to our MVC model?
Here is our form:
#model OurProject.Models.Input.InputModel
#{
ViewBag.Title = "Input";
}
<h2>
Inputs</h2>
<div id="inputKOApp">
#using (Html.BeginForm())
{
<!-- snip - lots of part of our form that work correctly -->
<div class="row-fluid">
<div class="control-group">
<div class="span8 control-label">
#Html.LabelFor(model => model.POSTransactionCodes)
</div>
<div class="controls">
<!-- These are the textboxes we would like to bind to MVC -->
<ul class="pull-right" data-bind="foreach: POSTransactionCodes">
<li>
<input data-bind="value: code" />
Delete</li>
</ul>
<button class="pull-right" data-bind="click: addPOSTransactionCode">
Add another POS Transaction Code</button>
#Html.ValidationMessageFor(model => model.POSTransactionCodes, null, new { #class = "help-inline" })
</div>
</div>
</div>
<!-- snip - more cshtml that is irrelevant to the problem -->
</div>
<input type="submit" value="Submit" />
}
</div>
<script type="text/javascript" src='~/Scripts/jquery-1.8.2.min.js'></script>
<script type="text/javascript" src='~/Scripts/knockout-2.1.0.js'></script>
<script type="text/javascript" src='~/Scripts/OP/OP.js'></script>
<script type="text/javascript" src='~/Scripts/OP/Input/OP.Input.Input.Form.js'></script>
<script type="text/javascript" src='~/Scripts/OP/Input/OP.Input.Input.Data.js'></script>
<script type="text/javascript">
var inputApp = $('#inputKOApp')[0];
OP.Input.Form.init(inputApp);
</script>
Here is our knockout.js script, OP.Input.Input.Form.js:
extend(OP, 'OP.Input.Form');
OP.Input.Form = function (jQuery) {
var TransactionCodeView = function () {
var self = this;
self.code = "";
};
//The ViewModel for the page
var ViewModel = function () {
var self = this;
//Fields
/* snip - lots of fields that work as expected */
self.POSTransactionCodes = ko.observableArray([]); //is a list of transaction codes
//Set up with initial data
/* I'm guessing that we won't need this function anymore since MVC will populate
* everything for us, but I'll leave it in until I'm far enough along to know
* I won't need to gut lots of stuff */
self.initialize = function () {
var c = function (data, status, response) {
/* snip - lots of fields that work as expected */
if (status === "success") {
if(data.POSTransactionCodes != null) ko.utils.arrayPushAll(self.POSTransactionCodes, data.POSTransactionCodes);
self.POSTransactionCodes.valueHasMutated();
} else {
}
};
OP.Input.Data.GetInput(c);
}
//When saving, submit data to server
self.save = function (model) {
var c = function (data, status, response) {
if (status === "success") {
} else {
}
};
OP.Input.Data.SaveInput(model, c);
}
//Modifying POSTransactionCodes array
self.removePOSTransactionCode = function (POScode) {
self.POSTransactionCodes.remove(POScode);
}
self.addPOSTransactionCode = function () {
self.POSTransactionCodes.push(new TransactionCodeView());
}
};
//Connect KO form to HTML
return {
init: function (elToBind) {
var model = new ViewModel();
ko.applyBindings(model, elToBind);
model.initialize();
}
};
} ($);
Here is our MVC model:
namespace OurProject.Models.Input
{
public class InputModel : IModel
{
//Snip - lots of properties that aren't interesting for this problem
[Required]
[DisplayName("POS Transaction Codes")]
public List<double> POSTransactionCodes { get; set; }
public InputModel()
{ }
/* I ommitted a few other methods that
* aren't relevant to this problem. */
}
}
I don't see how do you send the data back to the server but you need to name your inputs in way which allows model binding:
If you're binding to a list/collection your inputs should be name like:
<input type="text" name="CollectionPropertyName[index]" />
You can read about Model Binding To A List in this article
So you just need generate proper names for your inputs:
<input data-bind="value: code, attr: { name: 'POSTransactionCodes[' + $index() + ']' }" />
You should note that the above solution may only works if you're using the submit button and send the data form-urlencoded if you are sending the data as json you may need to tweak your serialization logic to make the model binder happy:
In this case your json should something like this:
{
//...
POSTransactionCodes: [ 1 , 3 ]
//..
}
Thanks to nemesv's answer show me light on this one.
But I need to have the "normal" name and id attribute for jquery validation. So I come up with the idea of writing my own data binder.
ko.bindingHandlers.nameId = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor(),
allBindings = allBindingsAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
var bindName = $(element).data('bind-name');
bindName = bindName.replace('{0}', valueUnwrapped);
$(element).attr({name : bindName, id : bindName});
}
};
And use it in html
<input
data-bind="value: qty, nameId: $index"
data-bind-name="inventory[{0}].qty" />
jsfiddle

How to change a class variable in PHP?

I'm sure there is an easy answer to this question, but for the life of me, I can't find it. I'm using PHP5 and I'm trying to change the value of a class variable, but it doesn't appear to change. For example, I have something like this:
<?php
include_once "../includes/global.php";
loadDAOs('yweightGroups','yweightCourses','yweightUsers','user','yweightData');
class yweight {
private $header_includes;
private $user;
private $yweightUser;
//Description:
// Constructor.
//Parameters:
// -none-
//Returns:
// -nothing-
function __construct() {
global $r_action;
global $r_page;
$this->user = login_required();
if(!$this->user || empty($this->user)){
die();
goHome();
}
$this->header_includes = "";
if(isset($r_action)) {
$this->$r_action();
}
else if (isset($r_page)) {
$this->$r_page();
}
else {
$this->draw();
}
}
//Description:
// Draws the YWeight page
//Parameters:
// -none-
//Returns:
// -nothing-
function draw() {
global $r_page;
global $colorDAO;
global $yweightUsersDAO;
ob_start();
?>
<script type='text/javascript' src="./yweight.js"></script>
<link rel="stylesheet" type="text/css" href="yweight.css" />
<?php
$this->header_includes .= ob_get_clean();
$col = $colorDAO->read(17);
print_top("",$this->header_includes,"resources","",$col->value,$col->fontcolor);
$users = $yweightUsersDAO->GetByUserID($this->user->id);
if(!$users){
echo "<div class='msg_failed'>You are not authorized to view this page.</div>";
die();
}
$this->yweightUser = $users;
echo serialize($this->yweightUser[0]);
?>
<div id="yweight_area"></div>
<script type='text/javascript'>
<?php
if($users[0]->yweightUsers_intern == 0)
echo "drawPage('main_participant');";
else
echo "drawPage('main_intern');";
?>
</script>
<?php
print_bottom();
echo ob_get_clean();
}
//Description:
// Draws the main intern page.
//Parameters:
// -none-
//Returns:
// -nothing-
function main_intern() {
ob_start();
echo "hello intern";
echo ob_get_clean();
}
//Description:
// Draws the main participant page.
//Parameters:
// -none-
//Returns:
// -nothing-
function main_participant() {
global $yweightDataDAO;
ob_start();
$this->yweightUser = $this->yweightUser[0];
echo serialize($this->yweightUser);
?>
<div id="banner_div">
<img class="banner" width="927" src="images/ParticipantsMain.jpg" />
<img id="tracker_btn" class="std_btn" src="images/trackerButton.png" />
<img id="summary_btn" class="std_btn" src="images/summaryButton.png" />
<img id="requirements_btn" class="std_btn" src="images/reqButton.png" />
</div>
<div id="discussion_board_input_div">
<textarea id="discussion_board_input" />
<?php
echo build_btn("green",100,25,"Submit","","","","",
'submit_post()',"margin-top:5px; margin-bottom:5px; float:right;");
?>
<div class="clear_floats" />
</div>
<div id="discussion_board_div">
</div>
<?php
echo ob_get_clean();
}
function submit_post(){
global $yweightDataDAO;
global $userDAO;
global $r_post;
echo serialize($this->yweightUser);
$userDataID = $yweightDataDAO->GetByUserID($this->yweightUser->user_id);
if($userDataID){
$userData = $yweightDataDAO->read($userDataID);
$userDiscussion = unserialize($userData->yweightData_discussionBoard);
}
$userDiscussion[$this->user->firstName . time()] = $r_post;
$userData->yweightData_discussionBoard = serialize($userDiscussion);
$yweightDataDAO->save($userData);
}
}
$recs = new yweight();
?>
submit_post() is an ajax called function. The error I'm getting is that it says $this->yweightUser is undefined. I didn't orignally include all of the code because I thought that I was just misunderstanding how class variables are declared.
You have a typo. Use __construct. Two (_ _) underscores. Your fooVariable is never getting set. After it gets set it works fine.
Update: You only set $this->yweightUser in your function draw() method. If you don't call draw() before ajax_post() or w/e, it will not be defined.
As mentioned above, fix the syntax errrors and it works, 2 underscores for the constructor and opening brace for the constructor and also brackets for arguments:
class foo {
protected $fooVariable;
function __construct () {
$this->fooVariable = "hello world";
$this->changeVariable();
}
function changeVariable(){
$this->fooVariable = "goodbye world";
$this->echoVariable();
}
function echoVariable(){
echo $this->fooVariable;
}
}
$foo = new foo();