JQuery Autocomplete - multiple data post not working - javascript

$("#textjawatan" + noid).autocomplete({
source: function( request, response ) {
$.ajax({
url: "pendaftar_table.php",
dataType: "json",
data: { term : "pe" } ,
success: function( data ) {
response( data );
}
});
},
minLength: 2,
select: function(event, ui) {
$("input#jawatan" + noid).val(ui.item.no);
}
});
when i use
data: { term : "pe" }
its work, but when i use
data: { term : "pe", id : "jawatan" }
its doesnt work, what is the problem ?

I actually had this problem not too long ago. Let me explain in quick words.
As jQuery Autocomplete explain in their site http://api.jqueryui.com/autocomplete/ jQuery Autocomplete only accepts TERM as output for server. Let me quote the page
Function: The third variation, a callback, provides the most
flexibility and can be used to connect any data source to
Autocomplete. The callback gets two arguments: A request object, with
a single term property, which refers to the value currently in the
text input. For example, if the user enters "new yo" in a city field,
the Autocomplete term will equal "new yo". A response callback, which
expects a single argument: the data to suggest to the user. This data
should be filtered based on the provided term, and can be in any of
the formats described above for simple local data. It's important when
providing a custom source callback to handle errors during the
request. You must always call the response callback even if you
encounter an error. This ensures that the widget always has the
correct state.
In other words, if you even add 250 extra hashes to the json dict, it will only work TERM to server side.
How did I fix this?
What I did was this. Based on jQuery docs, the source can also be an ARRAY, so i did an ajax call to my server BEFORE setting the jQuery autocomplete and then feed the autocomplete plugin.
Note: This is not a very good fix, and I'm aware of it. But I had to do it due to my work's details and is just an option.

Related

JQuery Autocomplete source not updating

I am using jquery-ui autocomplete plugin.
Here is how I've instantiated the autocomplete plugin.
//autofill
$( "#TextArea" ).autocomplete({
source: "search.php?option="+ option.toLowerCase(),
minLength: 3
});
On dropdown change, i am trying to change the option :
$('#Options').on('change', function() {
option = this.value.toLowerCase();
var teaxtarea = $('#TextArea');
//this is supposed to change the source string when the option value changes.
teaxtarea.autocomplete( "option", "source", "search.php?option="+ option);
}
});
I got the code to update the source string from the question below.
Jquery: Possible to dynamically change source of Autocomplete widget?
However, this solution doesn't seem to work for me.
I still get the first selected option even if i change the option in the dropdown.
Any help is greatly appreciated.
Suggest the following:
$("#TextArea").autocomplete({
source: function(req, resp){
var option = $('#Options option:selected').val().toLowerCase();
$.ajax({
cache: false,
url: "search.php",
data: {
option: option,
term: req.term
},
dataType: "json",
success: function(data){
resp(data);
}
});
},
minLength: 3
});
I think one issue is that if #Options is a <select> element, you need to find the selected child element:
$("#Options option:selected")
This ensures that you have the proper object and then you can call .val() upon it. If you need more help here, please update your post with an MCVE: https://stackoverflow.com/help/mcve
That may resolve the issue for you. If not, continue on.
Second, to ensure you are not caching, we can perform a more manual source capture.
When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must support CORS). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results.
So we replicate the same functionality with some added settings. So each time source is checked, the options will be checked and the term will be sent. We'll get the data back in JSON and send back to Autocomplete to be displayed.
Hope that helps.

jQuery ignore leading and trailing whitespace while sending request to remote URL

I am currently trying to make a simple jQuery autocomplete UI where the search term is sent back to a PHP backend, which in turn queries a MySQL database for matching term and sends back results. This works fine..except that, if I input 3-4 whitespaces, it sends a request as well, and this returns all results from backend. How do I configure jQuery autocomplete such that whatever term has been typed in, the search term that should go to the backend should have its leading and trailing whitespaces trimmed, and after trimming, if it is found to be a blank string, send no request at all?
I found multiple examples in SO, but all of them involve a built-in array of terms as example, I can't figure out how to configure the source parameter if its value is remote URL:
$("#myinput").autocomplete({
source: "http://127.0.0.1:8000/autoComplete/",
appendTo: "#search-holder",
response: function(e,y) {}
});
There's no easy answer for this one. I thought the search event allows an term overwrite but alas it doesn't. Nagaraju's answer is correct, only he didn't show actual implementation. Here's how it should look like
$( "#myinput" ).autocomplete({
source : function(request, response){
//trim the input value
request.term = request.term.trim();
if(request.term == ""){
//when empty, returns empty result
response([]);
}else{
//our own implementation of request to the server
$.get("http://127.0.0.1:8000/autoComplete/?term=" + request.term,
function(data) {
response(data);
});
}
}
});
Update your source function as the following:
source: function( request, response ) {
//Remove spaces
var matcher = new RegExp($.trim(request.term).replace(/ +/g, ""), "i" );
response($.grep(resources, function(value) {
return matcher.test( value);
}));
}
Use trim() to remove white-space from end and beginning of a string?
https://api.jquery.com/jQuery.trim/
Or you could do it at the backend.
http://php.net/manual/en/function.trim.php
Edit:
Why not just get all available autocompletion's once with an AJAX call when you load the page and store them in an array. This way the DB would only be bothered once when the page is loaded instead of every time there's a change in the input field. Also this would take some workload of the DB and the white space wouldn't be an issue.

Retrieve extra info from one option from autocomplete

I finally managed to retrieve a list from the available options related to the name searched from a field. Now, my goal is to retrieve some extra info when the user selects a specific option from the list. The JSON returns only the last name of the person and the user id which is an auto-increment field in the database. So I thought that I could send another JSON request to the server to actually return all the information available from the person specified from the user id. Is this considered bad practice ? Is there something alternative I am maybe missing ?
All in all, my code is here:
<script>
$(function() {
$( "#search" ).autocomplete({
delay: 0,
minLength: 2,
source: function(request, response) {
$.ajax({
url: 'search.php',
data: { term: request.term },
success: function(data) {
data = JSON.parse(data);
response($.map(data, function(item) {
return {
label: item.firstName,
value: item.firstName};
}));
}
});
}
})
});
</script>
So, how am I supposed to achieve this ?
I searched similar threads and read the doc in the official site but couldn't find a way to start. I think that somehow the results returned from the first call should be appended to DOM with anchor links, this code should be placed to the select property if I am not mistaken. But, I am very new to jquery and these web stuff and can't figure out the way.
Any help will be much appreciated. Thank you in advance.
It all depends on how much extra data you need returned.
If it's not much, then it makes sense to return the data as extra properties in a list of objects you are returning for the autocomplete results.
If you think you need too much extra data to make that viable, then in the autocomplete's select callback, you can just use the ID value to fetch all the additional info in an additional AJAX call to a second web service that returns the persons details for the passed in ID value.

search autocomplete performance with many records

I'm developing an application that is essentially a search bar. The source is a SQL table that has about 300,000 records.
Ideally, I would like to have some sort of autocomplete feature attached to this search bar. I've been looking into several ones like jquery autocomplete.
However, as one can imagine, loading all of these records as the source for the autocomplete is impossible. The performance would be abysmal.
So my question is, what is an efficient way to implement a search autocomplete feature for a source that contains thousands and thousands of records?
I thought of something like this. Essentially I'm querying the database each time they type something to get a list of results. However, querying a database via ajax doesn't seem optimal.
$( "#search" ).keyup(function( event ) {
$.ajax({
//query the database when the user begins typing, get first 1000 records
//set the source of the autocomplete control to the returned result set
});
});
You should not start querying the db on very first keyup, (not even in three-four) keyup.
For example, User is typing Albatross. When He hit 'A', if you do a Query search it will send you almost 300,000 results right away, cause every set of data must have the letter "A".
So, should ignore first few (3-5) letters. it will be better, if you can store the search keywords. Cache the top results, when 1-3 keyup you show the top search keywords. Auto complete might not be good feature for searching in a that big DB,
Last Tips for the problem, Your users use google and facebook everyday. They are more then 300,000 result for each of search in any of the applications above. Google or facebook does not show 1000 result at once. It is not good for UI Design or your Servers bandwidth. Just think, how can you categorizes and present the data to user, so that they get what they want and you keep your servers bandwidth and processing cost optimal.
always, remember the context.
Do not bind any events yourself. jQuery Autocomplete already performs bindings.
The proper way to implement this is to set the source: object to a an AJAX callback:
source: function (request, response) {
$.ajax({
url: 'yourQueryUrl.php', // <- this script/URL should limit the number of records returned
async: true,
cache: false,
type: 'GET',
data: {q: $('#searchBox').val()},
dataType: 'json',
success: function (data) {
response(data);
}
});
}
I am assuming you have added indexes to your table, if not that would be your first step, then if performance is insufficient and if your queries often repeat, you might want to look at this.
http://memcached.org/
or some other caching mechanism.
Upon request of some key you would return that key and add it to the cache, opon subsequent request for same key data would be read from cache instead of hitting database. That would reduce the load and increase the speed.
source: function (request, response) {
$.ajax({
url: 'yourQueryUrl.php', // <- this script/URL should limit the number of records returned
async: true,
cache: false,
type: 'GET',
data: {q: $('#searchBox').val()},
dataType: 'json',
success: function (data) {
response(data);
}
});

What does this javascript response function do?

I saw this code in another SO post: jQuery UI Autocomplete with ASP MVC
$("#CustomerID").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "/customer/search",
dataType: "json",
data: {
term: request.term
},
error: function(xhr, textStatus, errorThrown) {
alert('Error: ' + xhr.responseText);
},
success: function(data) {
response($.map(data, function(c) {
return {
label: c.Company,
value: c.ID
}
}));
}
});
},
minLength: 2,
select: function(event, ui) {
alert('Select');
}
});
I understand everything except the success function. I know that map is taking an array and mapping each value to a new object that has a label and value property and returning the new array, but I am not sure what response() does.
This object called response is a call back function passed to the function labeled source by the autocomplete method.
see Jquery UI Autocompleate
The third variation, the callback, provides the most flexibility, and can be used to connect any data source to Autocomplete. The callback gets two arguments:
A request object, with a single property called "term", which refers to the value currently in the text input. For example, when the user entered "new yo" in a city field, the Autocomplete term will equal "new yo".
A response callback, which expects a single argument to contain the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data (String-Array or Object-Array with label/value/both properties). It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
It appears to be a custom function that the original coder's code has. To the best of my knowledge this is not an inherent jQuery function.

Categories

Resources