Autocomplete not working on JSON file - php

I need your help. I'm trying to put an autocomplete on dynamically create text input but I have got some problem. I would like to use the JSON file because the ajax request took 1/2 sec and for my use it's too much.
Here is the code:
$(document).on('keydown.autocomplete',"[id$=_buy_mod]",function() {
$(this).autocomplete({
source: function(request,response) {
$.ajax({
ttpe: "GET",
url: "js/articoli.json",
data: {
term: request.term
},
dataType:'json',
dataFilter: function(data) {return data;},
success: function(data) {
response($.map(data,function(product) {
return {
label: product.label,
value:product.value
};
}))
},
})
},
minLength: 1,
select: function( event, ui ) {
var localid = $(this).attr('id');
var numerolocal = localid.match(/\d+/);
console.log(numerolocal);
$(this).val(ui.item.label);
$("[id$="+numerolocal+"_buy_id_mod]").val(ui.item.value)
return false;
}
});
Actually timing is good but autocomplete is not filtering data and it show me all possible words.
Here is the json file
[{"value": "1","label": "Panasonic Lumix L1"},
{"value": "10","label": "Sigma 17-50mm f 2.8 OS Canon"},
{"value": "11","label": "Canon 1000D"},
{"value": "1100D","label": "Canon 1100D"}
-------
How can I solve?

Related

Problem with json data source on ui autocomplete

I have a problem with my code. I receive data via ajax and it works, but the problem is that when I try to search for an element and all the elements appear so the search does not work properly.
JS code :
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
PHP code :
$data = array();
while($line = mysqli_fetch_object($liste_grp) ){
$data[] = array("label"=>$line->grp_nom,"value"=>$line->grp_nom ,"id"=>$line->groupement_id);
}
echo json_encode($data);
result
you should send the text you are searching for to ajax request so your autocomplete function should be
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque ,
term: request.term
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
request.term is your search text and in your example it is group text
and also you need to modify your mysql query and add condition (like)
for example
$rs = mysql_query("SELECT * FROM table WHERE colum LIKE '%" . $_POST['term'] . "%'");
and finally you can check https://jqueryui.com/autocomplete/#remote-jsonp
I would advise the following jQuery:
$( "#grp_name" ).autocomplete({
source: function(request, response) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id: request.term
},
success: function( data ) {
console.log(data);
response(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
This is a small change. This will send the request.term to your PHP Script. For example, if the user types "gro", this will be sent to your script and would be accessed via:
$_POST['marque_id']
This would assume your SQL Query is something like:
$stmt = $mysqli->prepare("SELECT * FROM table WHERE column LIKE '?%'");
$stmt->bind_param("s", $_POST['marque_id']);
$stmt->execute();
$liste_grp = $stmt->get_result();
$data = array();
while($line = $liste_grp->fetch_assoc()) {
$data[] = array(
"label" => $line['grp_nom'],
"value" => $line['grp_nom'],
"id" => $line['groupement_id']
);
}
$stmt->close();
header('Content-Type: application/json');
echo json_encode($data);
This uses the MySQLi Prepared Statement, and will help prevent SQL Injection. I also included the JSON Header as good practice. The result of search "gro" would be something like:
[
{
"label": "GROUPE DATAPNEU TEST",
"value": "GROUPE DATAPNEU TEST",
"id": 1
}
];
Thanks guys i found a solution it works better
i used tokeninput with many options
http://loopj.com/jquery-tokeni
$.ajax({
url:"ajax_get_societe_authorisation",
method:"POST",
scriptCharset: "iso-8859-1",
cache: false,
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
console.log(data);
$("#soc_name").tokenInput(data
,{
tokenLimit: 1,
hintText: "Recherche une société par son nom",
noResultsText: "Aucune société trouvé",
searchingText: "Recherche en cours ...",
onAdd: function (data) {
$("#soc_id").val(data.id);
},
onDelete: function (item) {
$("#soc_id").val("");
}
}
);
}
});

How to do jQuery autocomplete using an AJAX call to a PHP script?

I have the following jQuery code for the autocomplete,
$( "#text" ).autocomplete({
source: function( request, response ) {
$.ajax({
type: 'GET',
url: 'server.php',
dataType: 'json',
data: {
input: request.term
},
success: function(data) {
response( $.map(data, function(item) {
return {
label: item.Symbol + " - " + item.Name + " ( " + item.Exchange + " )"
}
}));
}
});
},
minLength: 1,
select: function( event, ui ) {
var symbol = ui.item.label.split(' ');
setTimeout(function() {
$('#text').val(symbol[0]);
},0);
}
});
Whenever a user enters a key in the textbox, an AJAX call is made to a PHP file. This PHP file will retrieve data from an API and update the suggestions list for the autocomplete feature?
I've got the following code in the PHP side,
<?php
if(!empty($_GET['term'])) {
$term = $_GET['term'];
$url = "http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input=".$term;
$j_response = file_get_contents($url);
$j_response = json_decode($j_response);
print json_encode($j_response);
}
?>
For some reason, the autocomplete isn't working for me- what am I doing wrong here?
In the PHP, you are trying to use $_GET['term'], but in the JavaScript your variable is called input. Change the data object to use term not input:
data: {
term: request.term
},

Passing an object to onSelect using Bootstrap3-typeahead

BootStrap3-TypeAhead
Hey all, I'm having trouble figuring out how I should be passing along an object of anything more than the default to onSelect for more extensive usage. Here's my code, any help would be greatly appreciated!
$("input[type='text']").typeahead({
onSelect: function(item) {
// Do things with the item object here.
},
items: 10,
ajax: {
url: "modules/scripts/Search.php",
timeout: 500,
triggerLength: 1,
method: "POST",
preDispatch: function (str) {
return {
String: str,
State: $("#"+$("#"+InputBox).attr("data-place")+"StateText").attr("data-sc")
}
},
preProcess: function (data) {
if (data.success === false) { return false; }
// I think I'd create the item object here, or pass it along?
var DD = [];
$.each(data, function(key, value) {
DD.push(value['City']+" - "+value['Zip']);
TempArr[value['ID']] = data[key];
});
return DD;
}
}
});
Seems you are using jQuery-UI autocomplete syntax. Typeahed use Bloodhound suggestion engine. Check Typeahead documentation.
Hearing Typeahead custom-event: typeaead:selected let ou retrieve the jQuery event object, the suggestion object, and the name of the dataset the suggestion belongs to.
I ended up solving this issue using the .remote.filter: function(obj) {} options. Here's a snip:
var AjaxOptions = {
type: "POST",
cache: false,
data: { limit: 10 },
beforeSend: function(jqXHR, settings){
// Manipulate settings.data to send more information than just the query string.
},
complete: function(data) {
// If desired, you could do a 'how long this query took' display here.
}
}
var InputArea = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.val); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
remote: {
cache: false,
url: 'scripts/Query.php?q=%QUERY',
filter: function (InputArea) {
return $.map(InputArea, function (data) {
// Do whatever you want with 'data', then return it
return {
foo: bar,
arnold: data.palmer
};
});
},
ajax: AjaxOptions,
}
});

Jquery autocomplete in codeigniter retrieving values but not displaying them

After a few hours of deciphering tutorials, I finally got codeigniter and jquery autocomplete to work with each other...kind of.
Firebug is displaying the correct search terms back in JSON format, but the drop down box is not displaying any text. If there are 2 results, it displays 2 empty rows.
you can see it 'not working' here: http://rickymason.net/blurb/main/home
JS:
$(document).ready(function() {
$(function(){
$( "#filter" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "http://rickymason.net/blurb/main/search/",
data: { term: $("#filter").val()},
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2
});
});
});
Controller:
public function search()
{
$term = $this->input->post('term', TRUE);
$this->thread_model->autocomplete($term);
}
Model:
public function autocomplete($term)
{
$query = $this->db->query("SELECT tag
FROM filter_thread ft
INNER JOIN filter f
ON ft.filter_id = f.filter_id
WHERE f.tag LIKE '%".$term."%'
GROUP BY tag");
echo json_encode($query->result_array());
}
Hopefully its an easy fix!
Thanks
Changing your code to something like this would work(I have tested in your site)
$( "#filter" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "http://rickymason.net/blurb/main/search/",
data: { term: $("#filter").val()},
dataType: "json",
type: "POST",
success: function(data){
var resp = $.map(data,function(obj){
return obj.tag;
});
response(resp);
}
});
},
minLength: 2
});
Copy and paste the above code block in your firebug console and then try the autocomplete. It will work. I tried in your site and it worked.
Secondly you dont need both $(document).ready(function() { and $(function(){ at the same time as they accomplish the same thing.
Check this section of jQuery UI autocomplete
Expected data format
The data from local data, a url or a callback can come in two variants:
An Array of Strings:
[ "Choice1", "Choice2" ]
An Array of Objects with
label and value properties: [ { label: "Choice1", value: "value1" },
... ]
Reference: $.map
Looking at this question on SO you need to setup your label and value fields on the response return. Try either arranging your PHP JSON output to match or map the return with something this the following (untested).
response( $.map(data, function(item){
return {
label: item.tag,
value: item.tag
};
})

How to get jQuery UI Autocomplete to work with json source?

This code is working:
$('input#city').focus(function() {
$(this).autocomplete({
source: '/autosuggest_cities?region_id=' + $('select#region').val(),
minLength: 1,
select: function(event, ui) {
$('#search-box #city_id').attr('value', ui.item.id);
}
});
});
But I don't like it because it hits the database each time the user key ups on the autosuggest text field. I rather hit the databse once and store all possible suggestions inside a variable and set that as the source for the autosuggest. So I tried this:
$.ajax({
url: '/autosuggest_cities',
type: 'get',
data: 'region_id=' + $('select#region').val(),
success: function(output) {
global.available_cities = output;
}
});
$('input#city').focus(function() {
$(this).autocomplete({
source: global.available_cities,
minLength: 1
});
});
When I console.log global.available_cities I do get a json object that looks right, for example:
[{"id":"19184","value":"Aiea"},{"id":"19516","value":"Anahola"},{"id":"20159","value":"Barbers Point"},{"id":"21999","value":"Camp H M Smith"},{"id":"16219","value":"Captain Cook"},{"id":"25135","value":"Eleele"},{"id":"15192","value":"Ewa Beach"},{"id":"26152","value":"Fort Shafter"},{"id":"27539","value":"Haiku"},{"id":"27546","value":"Hakalau"},{"id":"12603","value":"Haleiwa"},{"id":"27657","value":"Hana"},{"id":"11960","value":"Hanalei"},{"id":"27658","value":"Hanamaulu"},{"id":"11838","value":"Hanapepe"},{"id":"27916","value":"Hauula"},{"id":"27931","value":"Hawaii National Park"},{"id":"27933","value":"Hawi"},{"id":"28166","value":"Hickam AFB"},{"id":"8008","value":"Hilo"},{"id":"13747","value":"Holualoa"},{"id":"28457","value":"Honaunau"},{"id":"28470","value":"Honokaa"},{"id":"1221","value":"Honolulu"},{"id":"28471","value":"Honomu"},{"id":"28482","value":"Hoolehua"},{"id":"29284","value":"Kaaawa"},{"id":"29286","value":"Kahuku"},{"id":"8009","value":"Kahului"},{"id":"8010","value":"Kailua"},{"id":"29288","value":"Kailua Kona"},{"id":"11961","value":"Kailua-Kona"},{"id":"18379","value":"Kalaheo"},{"id":"29293","value":"Kalaupapa"},{"id":"29302","value":"Kamuela"},{"id":"8012","value":"Kaneohe"},{"id":"14283","value":"Kapaa"},{"id":"29322","value":"Kapaau"},{"id":"11792","value":"Kapolei"},{"id":"29342","value":"Kaumakani"},{"id":"8013","value":"Kaunakakai"},{"id":"11840","value":"Keaau"},{"id":"11962","value":"Kealakekua"},{"id":"29349","value":"Kealia"},{"id":"29359","value":"Keauhou"},{"id":"29386","value":"Kekaha"},{"id":"11777","value":"Kihei"},{"id":"29536","value":"Kilauea"},{"id":"18876","value":"Koloa"},{"id":"29739","value":"Kualapuu"},{"id":"14166","value":"Kula"},{"id":"29744","value":"Kunia"},{"id":"16950","value":"Kurtistown"},{"id":"8014","value":"Lahaina"},{"id":"12733","value":"Laie"},{"id":"8015","value":"Lanai City"},{"id":"30116","value":"Laupahoehoe"},{"id":"30148","value":"Lawai"},{"id":"8016","value":"Lihue"},{"id":"31035","value":"M C B H Kaneohe Bay"},{"id":"13539","value":"Makawao"},{"id":"31138","value":"Makaweli"},{"id":"31563","value":"Maunaloa"},{"id":"32160","value":"Mililani"},{"id":"32858","value":"Mountain View"},{"id":"15040","value":"Naalehu"},{"id":"33509","value":"Ninole"},{"id":"33931","value":"Ocean View"},{"id":"34146","value":"Ookala"},{"id":"34374","value":"Paauhau"},{"id":"34375","value":"Paauilo"},{"id":"34399","value":"Pahala"},{"id":"34400","value":"Pahoa"},{"id":"18798","value":"Paia"},{"id":"34493","value":"Papaaloa"},{"id":"34494","value":"Papaikou"},{"id":"8018","value":"Pearl City"},{"id":"34671","value":"Pearl Harbor"},{"id":"34774","value":"Pepeekeo"},{"id":"35531","value":"Princeville"},{"id":"12265","value":"Pukalani"},{"id":"35622","value":"Puunene"},{"id":"37200","value":"Schofield Barracks"},{"id":"39401","value":"Tripler Army Medical Ctr"},{"id":"40018","value":"Volcano"},{"id":"13879","value":"Wahiawa"},{"id":"40071","value":"Waialua"},{"id":"13759","value":"Waianae"},{"id":"15947","value":"Waikiki"},{"id":"18353","value":"Waikoloa"},{"id":"8019","value":"Wailuku"},{"id":"40072","value":"Waimanalo"},{"id":"13309","value":"Waimea"},{"id":"8020","value":"Waipahu"},{"id":"40083","value":"Wake Island"},{"id":"40900","value":"Wheeler Army Airfield"}]
But when I start typing in the text field awaitng suggestions I get this bizzare server error instead in my console:
414 Request-URI Too Large
The requested URL's length exceeds the capacity limit for this server.
What am I doing wrong? How can I use a json source for auto suggest without hitting the php script each time on keyup?
Phew got it working. All I had to do was add
dataType: 'json'
to my ajax call and all works fine. Will mark this is right answer in a few days when the system allows me.
try,
$('input#city').focus(function() {
$(this).autocomplete({
source: function( request, response ) {
response( global.available_cities )
},
minLength: 1
});
});
But the recommended way of doing this is,
$('input#city').focus(function() {
$(this).autocomplete({
source: function( request, response ) {
var region_id = $('select#region').val();
if( global.available_cities[region_id] != null ){
response( global.available_cities[region_id] )
}else{
$.ajax({
url: '/autosuggest_cities',
type: 'get',
data: 'region_id=' + region_id,
success: function(output) {
global.available_cities[region_id] = output;
response( global.available_cities[region_id] )
}
});
}
},
minLength: 1
});
});

Categories