jQuery autocomplete issue - each character on separate line - javascript

I am trying to get an autocomplete text box working. Here is the code that I have so far:
if ($action == 'find_products')
{
$dept = $_POST['dept'];
$stk_adddep = "
SELECT * FROM stocktake_products WHERE stocktake_id = '{$stocktake_id}' AND is_deli = 0 AND department_description LIKE '{$dept}%' LIMIT 10; ";
$result = db::c()->query($stk_adddep);
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$data[] = array(
'full_name' => $row['product_name'],
'value' => $row['product_name']);
}
echo json_encode($data);
die();
}
Div to display the text box:
<input type="text" placeholder="Name" id="customerAutocomplte" />
JS code:
$('#customerAutocomplte').autocomplete({
source: function( request, response ) {
var dept = $('#customerAutocomplte').val();
$.ajax({
url: '<?php echo Navigation::gUrl('/users/admin/stocktake_details_nonbcodeditems.php', array('stocktake_id' => $stocktake_id, 'action' => 'find_products'));?>',
type: 'POST',
data: {'dept':dept},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
minLength: 0
});
PHP part seems to be working fine, the response that I get is as follows:
[{"full_name":"Prince Hubert Cristal","value":"Prince Hubert Cristal"},{"full_name":"Schloer","value"
:"Schloer"},{"full_name":"Underberg 20ml","value":"Underberg 20ml"},{"full_name":"Odessa Vodka 20cl"
,"value":"Odessa Vodka 20cl"},{"full_name":"Marula","value":"Marula"},{"full_name":"Maderia Verdelho
15yr old","value":"Maderia Verdelho 15yr old"},{"full_name":"Madeira Malsmey 15yr old","value":"Madeira
Malsmey 15yr old"},{"full_name":"Hennessey 5cl","value":"Hennessey 5cl"},{"full_name":"Jack Daniels
35cl","value":"Jack Daniels 35cl"},{"full_name":"Madeira Bual 10 yr old","value":"Madeira Bual 10 yr
old"}]
However, the way that the results are displayed in the text box is incorrect. What gets displayed is the whole line "value":"Jack Daniels 35cl" for example which each character being a separate entry in the text box.

Try to use item.value in the callback function:
label: item.value value: item.value
$('#customerAutocomplte').autocomplete({
source: function( request, response ) {
var dept = $('#customerAutocomplte').val();
$.ajax({
url: '<?php echo Navigation::gUrl('/users/admin/stocktake_details_nonbcodeditems.php', array('stocktake_id' => $stocktake_id, 'action' => 'find_products'));?>',
type: 'POST',
data: {'dept':dept},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.value,
value: item.value
}
}));
}
});
},
autoFocus: true,
minLength: 0
});

Related

PHP & JavaScript - Variables

I just basically have a View with an Associative Array with Accidents Information.
The User will be able to click in the Country. When that happen I want to show them the information about accidents related with that country.
That information comes from PHP and the Click event is captured in JQuery...
How Can I insert the var country inside the index of the
associative array that came from PHP with an Index for each country?
.on('click', function(i, row) {
var country = row.label;
accident_chart.setData([{
a: <?php echo "".$charts['accidents_status'][**NEED var country value here**]['accidents']; ?>,
y: 'Accidents',
},
{
a: <?php echo $charts['accidents_status']['Qatar']['lost_time_accidents']; ?>,
y: 'Lost Time',
}
]);
});
You can't do that. Use AJAX instead to get the accident_chart data.
.on('click', function(i, row) {
var country = row.label;
$.ajax({
type: "GET",
url: "/get_accident_chart", // Just replace it with your PHP controller function that can access your $charts variable
data: {country: row.label},
dataType: "json",
success: function(data) {
accident_chart.setData(data);
},
error: function(data) {
return data;
}
});
});
In your PHP
get_accident_chart(){
$country = $_GET['country'];
$accident_chart = array(
array(
'a' => $charts['accidents_status'][$country]['accidents'],
'y' => 'Accidents'
),
array(
'a' => $charts['accidents_status']['Qatar']['lost_time_accidents'],
'y' => 'Lost Time'
)
);
echo json_encode($accident_chart);
}

jQuery autocomplete function brings the item from the database based on my typing word but result shows as just horizontal line of list

The jQuery autocomplete function brings the item from the database based on my typing word but result shows as just horizontal line of list. Attached image is showing how the result looks like.
HTML:
<form class="navbar-seach pull-center">
<div>
<input type="text" placeholder="Search Productstyle="width:550px; height:40px;padding-left: 10px;margin-top: 20px;" id="searchBox" onkeyup="if (event.keyCode === 13) {searchResults(this.value); this.value = '';}">
</div>
</form>
PHP:
include 'searchbox.php';
$switch_id = filter_input(INPUT_POST, 'switch_id', FILTER_SANITIZE_SPECIAL_CHARS);
if (isset($_POST['name_startsWith']))
$searchWordResults = $_POST['name_startsWith'];
else
$searchWordResults = null;
switch($switch_id){
case 1:
$userObj = new searchBox();
echo $userObj->autoComplete($searchWordResults);
break;
}
jQuery:
$("#searchBox").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "class/searchbox_switch.php",
dataType: "json",
data: { name_startsWith: request.term, switch_id: 1 },
success: function(data) {
response($.map(data, function(item){
return {
label: item.label,
value: item.value
};
}));
},
error: function(response) {
console.log(response.responseText);
}
});
},
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
searchResults(ui.item.label);
}
});
PHP (searchbox.php):
include '../dbConnect.php';
class searchBox {
public function autoComplete($name_startsWith) {
$letterSearch = $name_startsWith . "%";
$connectObj = new db_connect();
$dbh = $connectObj->connect();
$stmt = $dbh->prepare("SELECT product_name FROM products WHERE product_name LIKE :start");
$stnd = array();
$stmt->bindParam(':start', $letterSearch, PDO::PARAM_STR);
$stmt->execute();
$stnd = $stmt->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($stnd);
return $json;
}
}
OK got it. You are passing wrong key in your result. Your result data key is "product_name" And You are trying to access "label ". Try This solution:
success: function( data ) {
response( $.map( data, function(item) {
return {
label: item.product_name,
}
}));
},

Making clickable result list from Bootstrap typeahead and JSON

I want to make the result list for my Bootstrap typeahead list clickable and if the user clicks on any of the items in the dropdown list it will be redirected to the url [on my site, not external links] of the selected item. I made my changes regarding this Stackoverflow topic: jquery autocomplete json and clickable link through
The problem is, that I'm not into JS and Jquery and I can't tell why I get this error (Firefox Firebug Console output). I get this error everytime I enter any letter in my input textbox:
TypeError: it.toLowerCase is not a function bootstrap3-typeahead.min.js (1. line, 3920. column)
I see that the results of my PHP seems okay, so it must be something in the jQuery statement...
This is my result from the PHP:
[{"name":"TEXT-ONE","url":"\/textone-postfix"},{"name":"TEXT-TWO","url":"\/texttwo-postfix"},{"name":"TEXT-THREE"
,"url":"\/textthree-postfix"}]
This is my JQuery code:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
This is my PHP code:
<?php
require_once('../config/config.php');
require_once('../functions/functions.php');
require_once('../config/db_connect.php');
$query = 'SELECT name_desc FROM tbl_name ';
if(isset($_POST['query'])){
$query .= ' WHERE LOWER(name_desc) LIKE LOWER("%'.$_POST['query'].'%")';
}
$return = array();
if($result = mysqli_query($conn, $query)){
// fetch object array
while($row = mysqli_fetch_row($result)) {
$array = array("name" => $row[0], "url" => "/" . normalize_name($row[0])."-some-url-postfix");
$return[] = $array;
}
// free result set
$result->close();
}
// close connection
$conn->close();
$json = json_encode($return);
print_r($json);
?>
Can someone please help me what could be the problem here?
Thank you very much!
The problem was that the displayText wasn't defined:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
displayText: function(item) {
return item.value
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});

Getting error while using each loop under ajax

When i am trying each loop under Ajax call, i am getting error as:
TypeError: invalid 'in' operand e
Below is my Ajax call code
$.ajax({
type: "POST",
url: "/admin/counselormanagement/centername",
data: 'groupId='+valueSelected,
async: true,
success: function(arrCenter) {
$.each(arrCenter, function( intValue, arrValue ) {
console.log('<option value="' + arrValue['ID'] + '">'+ arrValue['CenterName'] +'</option>');
});
}
});
Response which i am getting back from server is :
Array (
[0] => Array
(
[ID] => 4
[CenterName] => test2
[ParentName] => 2
[Parent] => 3
[GroupName] => test
[Type] => 1
)
[1] => Array
(
[ID] => 8
[CenterName] => test21
[ParentName] => 2
[Parent] => 3
[GroupName] => test
[Type] => 1
)
)
I am using PHP as backend, whose code is :
$arrCenterName = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
print_r($arrCenter[0]);
die();
Use json_encode() in PHP to return response. And your JS code should be like:
PHP:
$arrCenterName = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
echo json_encode($arrCenter[0]);
die();
JQuery:
$.ajax({
type: "POST",
url: "/admin/counselormanagement/centername",
data: 'groupId='+valueSelected,
dataType: 'json',
async: true,
success: function(arrCenter) {
$.each(arrCenter, function( intValue, arrValue ) {
console.log('<option value="' + arrValue.ID + '">'+ arrValue.CenterName +'</option>');
});
}
});
Try to echo out your object using json_encode instead:
<?php
$arrCenterName = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
echo json_encode($arrCenter[0]);
die();

Autocomplete - user typing too fast - select typed input

I have the following code for multiple autocomplete of various fields. All works fine, but the problem is that my useres type too fast and ajax do not have time to load all results. Therefore, when somebody types the whole word (which is in the suggested list, but does not appear yet - is too slow), I need to use this word so that it behaves like the used clicked at this word in the list.
The answer might be this -> How do you trigger autocomplete "select" event manually in jQueryUI?, but I have no idea how it works with filling multiple fields. Do I need to do the mysql query again after onchange? Can anybody help please? I am rather a beginner so please sorry my not-knowing. I would possibly need a guidance step by step.
If I need this - where do I put it in my code?
$(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', {item:{value:$(this).val()}});
My code is like this:
$(".addmore").on('click',function(){
count=$('table tr:visible').length;
var data="<tr><td><div class='form-control rohy'><i class='fa fa-trash-o vymazat' id='"+i+"' onclick='reply_click(this.id);calculatecelkovoucenu();removeRow(this)' value='delete_"+i+"' data-val='"+i+"' style='font-size: 18px;color: #e70000;cursor: pointer;'></i><div></td><td><div class='form-control rohy'><span id='snum"+i+"'>"+count+".</span><div></td>";
data +="<td style='padding-right: 10px;'><input class='form-control rohy' type='text' id='produktyname_"+i+"' name='produktyname_"+i+"' placeholder='Kod zbozi' ></td> <td style='padding-right: 10px;'><input class='form-control rohy' type='text' id='produkty_no_"+i+"' name='produkty_no_"+i+"' placeholder='Popis zbozi' ></td><td style='padding-right: 10px;'><input class='form-control rohy' type='text' id='phone_code_"+i+"' name='phone_code_"+i+"' placeholder='Cena za 1 ks' oninput='calculate"+i+"();calculatecelkovoucenu();'></td><td style='padding-right: 10px;'><input class='form-control rohy' type='text' id='produktypocet_"+i+"' name='produktypocet_"+i+"' placeholder='Ks' oninput='calculate"+i+"();calculatecelkovoucenu();'></td><td><input class='form-control rohy' type='text' id='celkovacena_"+i+"' name='celkovacena_"+i+"' placeholder='Celkova cena' onchange='calculate"+i+"();calculatecelkovoucenu();' readonly></td></tr>";
$('table').append(data);
row = i ;
$('#produktyname_'+i).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'getprodukty.php',
dataType: "json",
method: 'post',
delay: 0,
data: {
name_startsWith: request.term,
type: 'produkty_table',
row_num : row
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 3,
select: function( event, ui ) {
var names = ui.item.data.split("|");
id_arr = $(this).attr('id');
id = id_arr.split("_");
$('#produkty_no_'+id[1]).val(names[1]);
$('#phone_code_'+id[1]).val(names[2]);
$('#produkty_code_'+id[1]).val(names[3]);
}
});
$('#produkty_code_'+i).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'getprodukty.php',
dataType: "json",
method: 'post',
delay: 0,
data: {
name_startsWith: request.term,
type: 'produkty_table',
row_num : row
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[3],
value: code[3],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 3,
select: function( event, ui ) {
var names = ui.item.data.split("|");
id_arr = $(this).attr('id');
id = id_arr.split("_");
$('#produkty_no_'+id[1]).val(names[1]);
$('#phone_code_'+id[1]).val(names[2]);
$('#produktyname_'+id[1]).val(names[0]);
}
});
$('#phone_code_'+i).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'getprodukty.php',
dataType: "json",
method: 'post',
delay: 0,
data: {
name_startsWith: request.term,
type: 'produkty_table',
row_num : row
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[2],
value: code[2],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 3,
select: function( event, ui ) {
var names = ui.item.data.split("|");
id_arr = $(this).attr('id');
id = id_arr.split("_");
$('#produkty_no_'+id[1]).val(names[1]);
$('#produkty_code_'+id[1]).val(names[3]);
$('#produktyname_'+id[1]).val(names[0]);
}
});
$('#produkty_no_'+i).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'getprodukty.php',
dataType: "json",
method: 'post',
delay: 0,
data: {
name_startsWith: request.term,
type: 'produkty_table',
row_num : row
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[1],
value: code[1],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 3,
select: function( event, ui ) {
var names = ui.item.data.split("|");
id_arr = $(this).attr('id');
id = id_arr.split("_");
$('#produkty_code_'+id[1]).val(names[3]);
$('#phone_code_'+id[1]).val(names[2]);
$('#produktyname_'+id[1]).val(names[0]);
}
});
i++;
});
getprodukty.php is as follows:
if($_POST['type'] == 'produkty_table'){
$row_num = $_POST['row_num'];
$name = $_POST['name_startsWith'];
$query = "SELECT kod,cena,popis FROM produkty where kod LIKE '".$name."%' ORDER by kod ASC LIMIT 5";
$result = mysqli_query($spojeni, $query);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['kod'].'|'.$row['popis'].'|'.$row['cena'].'|'.$row_num;
array_push($data, $name);
}
echo json_encode($data);
}
Thank you!
This is how I would handle it:
Store partial field value used for auto-complete
Perform ajax request
Check current value with stored value, if same proceed, if different abort (presumably the new addition has triggered a further ajax request with the newer value).

Categories

Resources