Bootstrap Select2 - Unable to populate via AJAX - php

I need some help figuring out what I am doing incorrectly. I am trying to populate the dropdown with users from my database. I am using Codeigniter and Firebug is giving me the error:
TypeError: j is undefined
VIEW
<input id="users" type="hidden">
<script>
$("#users").select2({
width: "element",
ajax: {
url: "localhost/index.php/get_clients",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
</script>
CONTROLLER
function get_clients() {
$this->load->model('users_model');
$result = $this->users_model->get_all_clients();
}
MODEL
function get_all_clients() {
$all_clients = $this->db->select('CONCAT(first_name, " ", last_name) as text, id', FALSE)
->get('clients')->result();
$rows = array();
foreach ($all_clients as $entry) {
$rows[] = $entry;
}
print json_encode($rows);
}
Which returns something like this:
[{"text":"John Smith","id":"433"},{"text":"Paul Sparks","id":"434"}]

Sorry, I was being stupid. I figured it out. User error.

Related

i am getting error as trying to get property of non object

i am getting sql result as array..Then it show me an error like `
trying to get property of non-object in controller in
`$rate=$product_det->sale_rate;
This sale_rate is a field in my table product.I am new to PHP. Can anyone help?
My model:
function get_productDet($item)
{
$this->db->select('*');
$this->db->from('product');
$this->db->where('id',$item);
$res=$this->db->get()->result_array();
return $res;
}
My controller:
function product_det()
{
$item=$this->input->post('item_id');
$quantity=$this->input->post('quantity');
$rate=$this->input->post('rate');
$amount="";
$cgst="";
$sgst="";
$igst="";
$product_det=$this->sale_model->get_productDet($item);
if(!empty($product_det))
{
if($rate=="" || $rate==0)
{
$rate=$product_det->sale_rate;
}
$amount=$rate*$quantity;
$cgst_per=$product_det->CGST;
$sgst_per=$product_det->SGST;
$igst=0;
}
echo $rate."-".$amount."-".$cgst."-".$sgst."-".$igst."";
}
My javascript function:
$.ajax({
url: '<?php echo base_url(); ?>sales/product_det',
data: ({"item_id":item_id,"quantity":quantity,"rate":rate }),
dataType: 'html',
type: 'post',
success: function(data)
{
alert(data);
}
});
You are using result_array() in your sql query.
Then use foreach loop to show your record like this
if(!empty($product_det))
{
foreach($product_det as $p_det){
if($rate=="" || $rate==0)
{
$rate=$p_det['sale_rate'];
}
$amount=$rate*$quantity;
$cgst_per=$p_det['CGST'];
$sgst_per=$p_det['SGST'];
$igst=0;
}
}
Since apparently you only need details of one product.
Change:
$res=$this->db->get()->result_array();
To:
$res=$this->db->get()->row_array();
Then, the result is an array not an object. To access the returned elements do the following instead.
Change:
$product_det->sale_rate;
$product_det->CGST;
$product_det->SGST;
To:
$product_det['sale_rate'];
$product_det['CGST']
$product_det['SGST'];
Hope this will help you :
In model just Replace
$this->db->get()->result_array();
With
$this->db->get()->row();
Your model should be like this :
function get_productDet($item)
{
$this->db->select('*');
$this->db->from('product');
$this->db->where('id',$item);
$res = $this->db->get()->row();
return $res;
}

Queing notification in PHP using AJAX with beep sound

I am building now a Queuing system for my helpdesk system. i have problem in detecting the changes of input value. I want to play the play_sound() function sound when the value of input is incremented. the curent value of input is coming from the rowCount in my SQL Query stored in variable.
screenshot picture link
Input
<input disabled type="text" id="needapproval" id="approval" value="0" class="center" />
My Script
<script type="text/javascript">
function play_sound() {
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'Kalimba.mp3');
audioElement.setAttribute('autoplay', 'autoplay');
audioElement.load();
audioElement.play();
}
activateMagic();
function activateMagic() {
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
$("#needapproval").val(res.data_count);
},
error: function(err) {
console.log(err);
}
});
}
}
</script>
PHP
require_once "connection.php";
class NeedApprovalStatus extends Connection{
public function needApproval() {
$count_approval = "SELECT * FROM job_request WHERE approval_status LIKE '%Need Approval%' ";
$stmt_count_approval = $this->db->prepare($count_approval);
$stmt_count_approval->execute();
$count = $stmt_count_approval->rowCount();
$data_count = [];
if ($count == 0) {
$data_count = [
'data_count' => 0
];
} else {
$data_count = [
'data_count' => $count
];
}
echo json_encode($data_count);
}
}
$need_approval = new NeedApprovalStatus;
$need_approval->needApproval();
I tried to use onchange event in jquery but it doesn't work. because i think onchange only trigger when you change value on input manually. Any ideas guys?
It would be easier to check the value inside the success function and call play_sound() from there.
function activateMagic() {
var value = 0;
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
var newValue = res.data_count;
if(newValue != value) {
play_sound()
$("#needapproval").val(value);
value = newValue;
}
}
...

jquery select2: error in getting data from php-mysql

I am testing select2 plugin in my local machine.
But for some reason. it is not collecting the data from database.
I tried multiple times but not able to find the issue.
Below are the code .
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function (params) {
return {
q: params.term // search term
};
},
results: function (data) {
lastResults = data;
return data;
}
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
i checked fetch.php and it is working fine. It is returning the data.
<?php
require('db.php');
$search = strip_tags(trim($_GET['q']));
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
I am trying to create tagging and it will check tag in database.
if tag not found then user can create new tag and it will save in database and show in user user selection.
At the moment i am not yet created the page to save the tags in database.
I tried using select2 version 3.5 and 4.0.1 as well.
This is first time is i am trying select2 plugin. So, please ignore if i did silly mistakes. I apologies for that.
Thanks for your time.
Edit:
I checked in firebug and found data fetch.php didn't get any value from input box. it looks like issue in Ajax. Because it is not sending q value.
Configuration for select2 v4+ differs from v3.5+
It will work for select2 v4:
HTML
<div class="form-group">
<div class="col-sm-6">
<select class="tags-select form-control" multiple="multiple" style="width: 200px;">
</select>
</div>
</div>
JS
$(".tags-select").select2({
tags: true,
ajax: {
url: "fetch.php",
processResults: function (data, page) {
return {
results: data
};
}
}
});
Here is the answer. how to get the data from database.
tag.php
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
//tags: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
delay: 250,
type: "POST",
data: function(term,page) {
return {q: term};
//json: JSON.stringify(),
},
results: function(data,page) {
return {results: data};
},
},
minimumInputLength: 2,
// max tags is 3
maximumSelectionSize: 3,
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
// return { id: term, text: text };
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_POST['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
With the above code i am able to get the data from database. I get help from multiple users from SO. Thanks to all of them.
However, i am still refining other areas like adding tag in database. Once it completed i will post full n final code.

My Select2 plugin is not returning any results from php script via ajax

I have been racking my brain for hours now trying to figure out why this is not working. Thanks in advance for anyone who can help.
Basically, I am trying to use json-encoded data from a php/mysql database query to populate the dropdown for the select2 plugin.
the HTML:
<input type="hidden" name="search-area" id="location-search" data-placeholder="Select an area" style="width:100%"/>
The Javascript:
$(document).ready(function() {
$(".select2").select2();
$("#location-search").select2({
ajax: {
url: "location-data.php",
dataType: 'json',
data: function (term) {
return {
q: term
};
},
results: function (data) {
return { results: data.text };
}
}
});
})
The PHP Script 'location-data.php':
<?php
include 'db/db-connect.php';
$query = "SELECT townID, town FROM towns WHERE town LIKE '%a%' ORDER BY town";
$result = $db->query($query);
$numtowns = $result->num_rows;
if($numtowns != 0) {
while($row = $result->fetch_assoc()) {
$answer[] = array("id"=>$row['townID'], "text"=>$row['town']);
}
}
else {
$answer[] = array("id"=>"0", "text"=>"No Results Found...");
}
echo json_encode($answer);
?>
Now i have looked at the location-data.php page in my browser and it is displaying in the correct format, see below.
[{"id":"1","text":"basildon"},{"id":"2","text":"billericay"},{"id":"7","text":"eastwood"},{"id":"12","text":"hanningfield"},{"id":"5","text":"maldon"},{"id":"11","text":"ongar"},{"id":"6","text":"rayleigh"}]
Whenever I attempt to use the select2 box, all it displays is 'searching...' and never displays results.
Thanks again for any help that can be given.
try changing the result function to return data. select2 needs an array of id,text pairs. i suspect you're seeing a javascript error in your browser that data.text doesn't exist.
results: function (data) {
return { results: data };
}
add more:
formatResult: formatValues,
formatSelection: selectValues,
Create function formatresult and selectValues:
function formatValues(data) {
return data.text;
}
function selectValues(data) {
return data.id;
}

Search for a table within a database in Laravel 4 PHP Framework

I am trying to set up search for a table within database in mine within the Laravel 4 PHP Framework. I am using jquery to accomplish this. I have a table "artists", that I am trying to allow a user to search through. I have a model "Artist.php", and a controller "SearchController.php" that I am using to control the logic. Finally, I have a view "search.blade.php" that I am using as the user facing file. Here is the relevant code:
SearchController.php:
public function show_search() {
$limit = 10;
if(isset($_GET['mode']) && !empty($_GET['mode'])) {
switch($_GET['mode']) {
case 'autocomplete':
if(isset($_GET['keywords']) && !empty($_GET['keywords'])) {
$query = htmlspecialchars($_GET['keywords']);
$query = mysql_real_escape_string($query);
$results = Artist::search_artists($query);
$data = array();
$i = 0;
if(isset($results) && !empty($results)) {
foreach($results as $result) {
if (strlen(strstr($result->stage_name, 'artists')) == 0) {
if($i < $limit) {
$data[$i] = $result;
$i++;
}
}
}
}
exit;
}
break;
}
}
return View::make('search.search');
}
Artist.php:
public static function search_artists($query) {
$search_artists = DB::table('artists')
->where('artists.stage_name', 'LIKE', $query)
->orderBy('created_at', 'DESC')
->get();
return $search_artists;
}
search.blade.php:
<input type="text" class="search" id="inputSearch" /><br />
<div id="divResult"></div>
<script type="text/javascript">
$(function(){
$(".search").keyup(function() {
var inputSearch = $(this).val();
var data = {mode : 'autocomplete', keywords : inputSearch};
if(inputSearch!='') {
$.ajax({
type: "GET",
url: "/search/search",
data: data,
cache: false,
success: function(html) {
console.log(html);
$("#divResult").html(html).show();
}
});
}
return false;
});
});
</script>
I call all of this with the route:
Route::get('/search/search', array('uses' => 'SearchController#show_search'));
When I run this and I type things into the search box, I see in the javascript console it reads:
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.
and the results don't display under the search box. Any idea what could be going wrong? Thank you for your help.
The javascript warning is caused by your return false;. If you need it (doesn't seem necessary for the keyup event unless you want to catch the enter key), you should do something like:
$(".search").keyup(function(e) {
e.preventDefault(); // prevent the default action of the event
I am not familiar with Laravel, but it seems to me that you are not getting any results because you are not doing anything with the $data variable in your controller.
I would guess you need something similar to:
return View::make('search.search', $data);
to pass the variable to your view.

Categories