How can I fetch data in autosuggest textbox from server/database? - javascript

I have created an autosuggest textbox that is fetching data from defined array.How can I make it fetch data from server?
Following is my code-
HTML code-
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>autocomplete demo</title>
<link rel="stylesheet" href="jquery-ui.css">
<script src="jquery-1.10.2.js"></script>
<script src="jquery-ui.js"></script>
</head>
<body>
<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">
<script>
var tags = [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ];
$( "#autocomplete" ).autocomplete({
source: function( request, response ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
response( $.grep( tags, function( item ){
return matcher.test( item );
}) );
}
});
</script>
</body>
</html>
Javascript files are of too much length.I can't paste them here.

There are number of ways in which you can populate an autocomplete box with data from your server. One of the easiest way to do so is, retrieve the data from your server and store it locally, and then use it.
var searchData = [];
$.get("ajax/mydata", function( data ) {
searchData.push(data);
});
And then, carry on with the autocomplete part.
$( "#autocomplete" ).autocomplete({
source: searchData,
...
});
Also, have a look at the jQuery UI Autocomplete documentation at http://jqueryui.com/autocomplete/
ps. Don't forget to mark this as the answer if it works for you.

Related

Autocomplete field with JSON data from external url (Steam API)

I am working on an input field that is autocompleted with names from this link(steam API):
http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json
or
http://api.steampowered.com/ISteamApps/GetAppList/v0001
I would also like the field to return the id of the game despite the name being insered into it.
So far after browsing the forums I put together this but it doesn't quite work:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$("#tags").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json",
data: { query: request.term },
success: function (data) {
var transformed = $.map(data, function (el) {
return {
label: el.appid + " - " + el.name,
id: el.appid
};
});
response(transformed);
},
error: function () {
response([]);
}
});
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
For the autocomplete part I chose to use jQuery autocomplete function: https://jqueryui.com/autocomplete/ however I am open to other methods.
Edit: Fixed syntax error on line 31 but the code still isn't working.
JSFiddle: https://jsfiddle.net/vxej2L5g/
In the success block you are assigning a label and id. In the label you have assigned name, and in id the appid. We can modify this to format the label like this:
success: function (data) {
var transformed = $.map(data, function (el) {
return {
label: el.appid + " - " + el.name,
id: el.appid
};
});
response(transformed);
},
There is a syntax error in your Javascript on line 31 (basically you have an extra closing parenthesis and semicolon).
The JSON response for the API you are calling wraps the list of apps.

jQueryUI: Autocomplete with large data is hanging browser

I am using jQueryUI's autcomplete in my project. I have a autocomplete text where user search something and corresponding data comes in drop down.
With a small data set, it's working fine. The problem arises when the data set is large. I have almost 1L records with unique values which I've attach as source to autocomplete.
Now as soon as user enter search string in the text bar the browser hangs cause because of the processing that autocomplete of jQueryUI does.
I want to know how can I optimize it or make it faster so that the borwser does not hang. Here's the plunkr I have created to play. And this is what I am doing to attach source to autocomplete.
$("#tags").autocomplete({
source: availableTags
});
Instead of show all 50000 records show only top 10. Minimum search character length increased from default 0 to 2
$(function () {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
for (var i = 0; i < 50000; i++) {
availableTags.push('abc' + i);
}
$("#tags").autocomplete({
minLength: 2,
source: function (request, response) {
var results = $.ui.autocomplete.filter(availableTags, request.term);
response(results.slice(0, 10));
}
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
Add a limit of displayed results, like ten.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script>
$( function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
var max= 10000;
// change max to 1000000 ie. 1L and it hangs.
for(var i=0;i<max;i++){
availableTags.push(i+'');
}
$("#tags").autocomplete({
source: function(request, response) {
var results = $.ui.autocomplete.filter(availableTags, request.term);
response(results.slice(0, 20));
}
});
} );
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
Please check this
I faced the same issue and solved the issue by overriding the _renderMenu function with a custom function that renders the itemlist asynchronously.
First you define an asynchronous rendering function AND a function to stop the asynchronous rendering (please read the API documentation, so you know what you are doing):
let customACFunctions = {
asyncRenderMenu: function(ul, data) {
let batchSize = 20;
let autoc = this; //refers to the autocomplete widget.
function renderNextBatch(){
$(ul).find('li.autocomplete-spinner').remove();
let j = 0;
while (j < batchSize && data.length > 0) {
autoc._renderItemData(ul, data.shift());
j++;
}
//normally, the widget internals add this class to each list item, now
//we'll have to do it ourselves
$(ul).find('li:not(.ui-menu-item)').addClass('ui-menu-item');
if (data.length > 0) {
//add an 'item' to indicate that the list is still being 'loaded'
$(ul).append('<li class="ui-menu-item autocomplete-spinner"><a>Laden...</a></li>');
customACFunctions._asyncRenderingTimeoutId = setTimeout(renderNextBatch, 1);
}
}
renderNextBatch();
},
_asyncRenderingTimeoutId: null,
stopAsyncRendering: function() {
if (customACFunctions._asyncRenderingTimeoutId) {
clearTimeout(customACFunctions._asyncRenderingTimeoutId);
customACFunctions._asyncRenderingTimeoutId = null;
}
}
};
Next, you will assign the asynchronous rendering function to the widget:
$("#autocompleteId").data("ui-autocomplete")._renderMenu = customACFunctions.asyncRenderMenu;
Next, we will also have to stop this asynchronous rendering - of which our widget is unaware - when we change the search query. (Otherwise you will get a mess in your item list...) If you have not defined an event handler for the 'search' event, you can do:
$("#autocompleteId").on("autocompletesearch", customACFunctions.stopAsyncRendering);
If you have defined an event handler for the search event, than invoke this function from that event handler.
And best is also to stop rendering when the user selects an item. If you have defined a function for the 'select' event, then invoke this function in your event handler. Otherwise:
$("#autocompleteId").on("autocompleteselect", customACFunctions.stopAsyncRendering);
I recommend to limit the data you fetch from somewhere other than local device.cause not displaying them does not mean you have not allotted memory for them. although doing so would help also.
P.s : apology for my poor english
Due to large volume of data set, some time this issue occurs. Browser get hang while loading large amount of data,
Here, first filter will work to slice a array and will return the decided accurate values from the whole data.
$("#postcode").autocomplete({
source: function (request, response){
var results = $.ui.autocomplete.filter(your_array,request.term);
response(results.slice(0, 10));
}
});
hope this will works for you

How to do '#somename' like twitter functionality? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am trying to do a functionality like which happens on Twitter.
If I write #J in text box, a list should appear show with autocomplete starting names "Javascript", "Java", "JQuery".
When I select Jquery, it should display in a TextBox. I got the autocomplete code from Jquery. But I am unable to do this '#' functionality.
Below is the code which I have done till now:
<html lang="en">
<head>
<meta charset="utf-8">
<title>autocomplete demo</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">
<script>
var tags = [ "Javascript", "Jquery", "Java" ];
document.getElementById('autocomplete').onkeypress = function (e) {
if (e.keyCode === 64 ) {
$( "#autocomplete" ).autocomplete({
source: function( request, response ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
response( $.grep( tags, function( item ){
return matcher.test( item );
}) );
}
});
}
else
{
return false;
}
};
</script>
</body>
</html>
Try this:
http://jsfiddle.net/gtnf41co/5/
It checks input value starts with #:
if (this.value.search("#") == 0)
then takes out the # in the request term
request.term.replace("#", "")
You can do this with the autocomplete functionality by adding the # symbol to your tags:
<script>
var tags = [ "#Javascript", "#Jquery", "#Java" ];
$( "#autocomplete" ).autocomplete({
source: tags
});
</script>

JavaScript Variables and User Input

Situation:
Currently I have a search box utilizing jQuery’s autocomplete plugin that allows the user to search for a sport’s team and then once found select on a submit button where it appends the team as a list item (preferable functionality would be when the user clicks on the actual team to append the item but at this point I am unsure of how to apply an on click function to the autocomplete drop down – suggestions welcome).
I am looking for a way to associate the newly appended list item to a predefined class or id so that certain formatting and displays are applied to the appended list item as soon as it is appended.Basically the user can search for any team in the NHL, NFL, etc. and I need to pair text colors and logos with them depending on which team they select - but the logos will appear separately in the body not in the list.
Example Code:
<!doctype html>
<html>
<head>
<title>TEST</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style type="text/css">
</head>
<body>
<div class="ui-widget">
<input id="tags" type="text" placeholder="Search Teams"/>
<input id="submit" type="submit"/>
</div>
<ul class="target">
</ul>
<script>
$(function() {
var availableTeams = [
"Boston Red Sox",
"New England Patriots",
"Boston Celtics",
"Boston Bruins",
"New England Revolution"
];
$( "#tags" ).autocomplete({
source: availableTeams
});
});
$('#submit').click(
function() {
var term = $('#tags').val();
$('.target').append("<li>"+term+"</li>");
}
);
</script>
</body>
</html>
I have tried using a combination of if statements and document.getElementById to try and alter the html content but I cannot piece my thoughts together.
My thoughts:
if (tags == "Boston Red Sox") {
Then append "Boston Red Sox" with specific formatting as a list Item and corresponding logo below.
} else {
dont do anything
}
http://jsfiddle.net/kumcav30/ (ideally when appended it would resemble something like the fiddle). Any input is greatly appreciated.
jQuery will let you create elements and alter them before you add them to the document. So you could do something like:
$('#submit').click(
function() {
var term = $('#tags').val();
var newelement = $("<li>"+term+"</li>");
if (term == "Boston Red Sox") {
newelement.addClass("your-class");
//whatever else you need to do
}
$('.target').append(newelement);
}
);
How about a for loop?
$(function(){
var availableTeams = [
"Boston Red Sox",
"New England Patriots",
"Boston Celtics",
"Boston Bruins",
"New England Revolution"
];
$( "#tags" ).autocomplete({
source: availableTeams
});
var availableLogos = [
"redSox",
"patriots",
"celtics",
"bruins",
"englandRevolution"
];
function teamstyle(term){
var l = availableTeams.length;
for (var i = 0; i < l; i++){
if (term == availableTeams[i]){
var newelement = "<li class="+ availableLogos[i] +">"+term+"</li>"
$('.target').append(newelement);
}
}
}
$('#submit').click(function() {
var term = $('#tags').val();
teamstyle(term);
});
});
then you could use css like:
.redSox {color: red; background: url('path/to/logo.png');}
.bruins {color: yellow;}
....
Your question is a bit confusing. consider narrowing it down to what you want to achieve (:

Filter a list and requesting data via ajax

im new to javascript and phonegap and im sitting here the whole day and try to solve this problem.
I have a list and i want to filter some data. And before i filter it, i want to download some data from a server and add it to the list. ( the list is local and if someone uses the search function, new data should pop up too).
The idea is that i create the list with jquery and use the listviewbeforefilter-event to download the data from a server and add it to the list. Then jquery should filter the list.
It works fine when i search filter for 2 chars.
But this doesnt work as expected when i search for more than 2 chars.
I receive the correct data from the server and it will be added to my list but the there is no more filtering in my original list. So i see my original list + the loaded data.
Also the console.log("second") is shown first and then console.log("first). Somehow jquery/phonegap skips the .then part and then comes back to it.
I tried to put the 3 lines ($ul.html( content );$ul.listview( "refresh" );$ul.trigger( "updatelayout");) below the second console.log and then the filter of my local data works but the data from the server wont be shown.
I hope someone can help me with this weird problem.
Heres my code for the listviewbeforefilter-event:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<title>Listview Autocomplete - jQuery Mobile Demos</title>
<link rel="stylesheet" href="css/jquery.mobile-1.3.2.min.css" />
<script src="cordova.js"></script>
<script src="js/jquery-2.0.3.min.js"></script>
<script src="js/jquery.mobile-1.3.2.min.js"></script>
<script>
$( document ).on( "pageinit", "#myPage", function() {
$( "#autocomplete" ).on( "listviewbeforefilter", function ( e, data ) {
// this is a second list which is a backup. It is needed because after each search the original list is flooded with old entries.
var content = document.getElementById("autocomplete2").innerHTML;
var requestdata = "";
var $ul = $( this );
$input = $( data.input ),
value = $input.val();
// ajax call returns cities with at least 3 characters
if ( value && value.length > 2 ) {
$.ajax({
url: "http://gd.geobytes.com/AutoCompleteCity",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
// The response is saved in html which i append to the original content
.then( function ( response ) {
var html = "";
console.log("first");
$.each( response, function ( i, val ) {
html += "<li>" + val + "</li>";
});
content = content + html;
$ul.html( content );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
console.log("second");
}
});
});
</script>
and that is the body with the list:
</head>
<body>
<div data-role="page" id="myPage">
<div data-role="header" data-theme="f">
<h1>Listview </h1>
</div><!-- /header -->
<div data-role="content">
<div class="content-primary">
<ul id = "autocomplete" data-role="listview" data-filter="true" data-filter-placeholder="Search people..." data-filter-theme="d"data-theme="d" data-divider-theme="d">
<li data-role="list-divider">A</li>
<li>Adam Kinkaid</li>
<li>Alex Wickerham</li>
<li>Avery Johnson</li>
</ul>
</div><!--/content-primary -->
</div><!-- /content -->
<script type="text/javascript" charset="utf-8">
$(function(){
$( "#autocomplete2" ).hide();
});
</script>
<ul id = "autocomplete2" data-role="listview" data-filter-theme="d"data-theme="d" data-divider-theme="d">
<li data-role="list-divider">A</li>
<li>Adam Kinkaid</li>
<li>Alex Wickerham</li>
<li>Avery Johnson</li>
</ul>
</div><!-- /page -->
</body>
</html>
i fixed the issue. I changed the code :
content = content + html;
$ul.html( content );
to
$ul.append( html);
i made a custom filter and recognized that the .then was always called AFTER the filter began.
Thats really weird because this method listviewbeforefilter should do everything before the filtering begins. I guess its because the ajax takes so long and will be skipped but later coming back to the .then method when the response received. I thought maybe async:false would help, but nope.
So basically it filters my local data and hides the list which are not needed and than i append the received data to the list.

Categories

Resources