I am trying to do the following. I have a date picker. When I select a date (during data change event), I am doing a ajax call to get data that I need to populate in a autocomplete drop down. When the page loads for the first time, the autocomplete box will be empty. As and when the date is changed or selected, the autocomplete box should populate accordingly. Please check my code below.
When I initiate the dataSrc variable, the drop down loads for the first time without any issues.
The issue that I am having is with the dynamic population, the data that I am fetching from the ajax call is not being set in the autocomplete source dynamically.
Please advice.
var dataSrc = [];
$(document).ready(function() {
$("#dropdownselector").autocomplete({
source : dataSrc,
change : function(event, ui) {
$("#selector").val(0);
$("#selector").val(ui.item.id);
}
}).focus(function() {
$(this).autocomplete("search", " ");
});
$('#dateselector').on("changeDate", function() {
$.ajax({
type : "GET",
url : "../getDropDownData",
data : {
"dateSelected" : $('#dataSelected').val()
},
contentType : "application/x-www-form-urlencoded; charset=utf-8",
dataType : "json",
async : true,
cache : false,
success : function(data) {
dataSrc = JSON.stringify(data);
},
error : function(data) {
alert('There was an error while fetching data.')
}
})
});
});
dataSrc = JSON.stringify(data); replaces what dataSrc points to. It does not change the original array element that was given to the autocomplete.
You could try pushing all the elements from the data into the dataSrc, which would cause the array that dataSrc originally pointed to, to not change, but get new values.
Or if that does not work, you may have to use the https://api.jqueryui.com/autocomplete/#method-option method to change the source option for the autocomplete.
$("#dropdownselector").autocomplete( "option", "source", data);
Inner your success function you need to destroy the old autocomplete and redraw it. Maybe, you need to create a function to create the autocomplete ('drawAutocomplete').
...
success : function(data)
{
dataSrc = JSON.stringify(data);
$( "#dropdownselector" ).autocomplete( "destroy" );
drawAutocomplete();
},
...
Related
I have an autocomplete field, and on type I go to the PHP/Database to retrieve the matching options.
Thing is, my suggestion list isn't exactly matches of the text. I explain:
Say I type "Jon". My list will bring from the database "John Doe", "Jonatan", etc. Only "Jonatan" will be visible as the suggestion to the input, but I do need them all, because it considers approximation (there's a soundex element on my backend search).
My JavaScript/Ajax code:
function prePatientsList(){
//I'm limiting search so it only starts on the second character
if (document.getElementById("name").value.length >= 2) {
try
{
listExecute.abort();
}catch(err) {
null;
}
var nome= $("#name").val();
var nomeList = "";
listExecute = $.ajax({
url: '/web/aconselhamento/Atendimento/PrePacientesAutocomplete',
type: "POST",
async: true,
datatype: 'json',
data: { nome: nome}
}).done(function(data){
source = JSON.parse(data);
});
$(function() {
$("input#nome").autocomplete({
source: source,
// I know I probably don't need this, but I have a similar component which has an URL as value, so when I select an option, it redirects me, and I'll apply you kind answer on both.
select: function( event, ui ) {
ui.item.label;
}
});
});
}
}
Thanks.
I think you'd have to set your remote endpoint directly as the autocomplete's source (e.g. similar to https://jqueryui.com/autocomplete/#remote) so that it's the backend which does all the filtering. Right now, the autocomplete effectively thinks you've fed it a static list of options from which further filtering should take place, and therefore it decides to handle the filtering itself.
Your code can be as simple as this I think, no need to have a separate handler or an ajax request outside the scope of the autocomplete.
$(function() {
$("input#nome").autocomplete({
minLength: 2, //limit to only firing when 2 characters or more are typed
source: function(request, response)
{
$.ajax({
url: '/web/aconselhamento/Atendimento/PrePacientesAutocomplete',
type: "POST",
dataType: 'json',
data: { nome: request.term } //request.term represents the value typed by the user, as detected by the autocomplete plugin
}).done(function(data){
response(data); //return the data to the autocomplete as the final list of suggestions
});
},
// I know I probably don't need this, but I have a similar component which has an URL as value, so when I select an option, it redirects me, and I'll apply you kind answer on both.
select: function( event, ui ) {
ui.item.label;
}
});
});
See http://api.jqueryui.com/autocomplete/#option-source for more info.
I have a table that i load with AJAX and edit with Jeditable.
This is how i start my function:
function refresh_page() {
var tableElm = $('#refresh');
$.ajax({
url: 'assets/php/ritsys/my_table.php',
success: function(data) {
if (!($("*:focus").is("textarea, input, select, date, time")) ) {
tableElm.html(data)
}
$(function(){
$('.edit').editable('assets/php/ritsys/save.php', {
indicator : '<img src="assets/css/smoothness/images/ui-anim_basic_16x16.gif">'
});
});
setTimeout(refresh_page, 1500);
}
}); };
This works fine and i added the if (!($("*:focus").is("textarea, input, select, date, time")) ) { line because i had problems with the data refreshing while i was editing something in the table.
But after i added this everytime when i update a value in the table firstly it shows me the indicator image, then the old value and after that the new value.
Before it would briefly show the indicator and then the new value. Can somebody help me to cut out the step where it shows the old data?
It would be greatly appreciated!
Does the script assets/php/ritsys/save.php return the "new" value? You should return the "new" value, not the "old" value. The returned value will be shown when the request is complete.
I am trying to get the pasted contents of a form text field to trigger an AJAX action which connects to a php script to deal with the data and then sends the relevant response.
The php script is working perfectly so I know the problem isn't there.
The jQuery function also works perfectly, by alerting whatever is pasted into the text field if I do this
$(document).ready(function(){
$('input').on('paste', function () {
var capture = this;
setTimeout(function () {
var url = $(capture).val();
alert (url);
}, 100);
});
});
But when I try to add the AJAX business it all fails.
I'm obviously doing it wrong but I don't know the correct way to do it.
The way I'm calling AJAX is the same method I use in a whole bunch of other scripts and it works fine in those so it must be to do with where it's being called.
I've tried (left off the doc ready to save clutter) :
$('input').on('paste', function () {
var capture = this;
setTimeout(function () {
var url = $(capture).val();
}, 100);
var data = {
'action': 'myAction',
'security': $( '#my-nonce' ).val(),
'url' : url,
'check' : check
};
$.post(myajax.ajaxurl, data, function(response) {
alert(response);
}
});
And also tried :
$('input').on('paste', function () {
var capture = this;
setTimeout(function () {
var url = $(capture).val();
var data = {
'action': 'myAction',
'security': $( '#my-nonce' ).val(),
'url' : url,
'check' : check
};
$.post(myajax.ajaxurl, data, function(response) {
alert(response);
}
}, 100);
});
And I've also tried setting the url var directly in the data var :
var data = {
'action': 'myAction',
'security': $( '#my-nonce' ).val(),
'url' : $(capture).val(),
'check' : check
};
But nothing is working.
I suspect this is to do with the setTimeout function.
Is there a specific way of firing an AJAX call when also using setTimeout?
Just for clarity. I'm trying to trigger an AJAX call on paste event.
try to increase the time, I mean
setTimeout(function(){...
,1000}
try experimenting with different times.
If you get the answer then your post call is eating up the time.
I have used JQuery UI autocomplete to cut down on the list of parts I have to display in a drop down, I am also using json to pass the list of parts back but I am failing to see the results, I am sure this is to do with my limited understanding of JQuery's Map function.
I have the following json
{"parts":[{"partNumber":"654356"},{"partNumber":"654348"},{"partNumber":"654355-6"},{"partNumber":"654355"},{"partNumber":"654357"},{"partNumber":"654357-6"},{"partNumber":"654348-6"}]}
which on JSONLint is validated correct
I have viewed the post and response utilising Firebug and seen them to be correct but my auto complete does not seem to display, the closest I have got it to doing so, was when I displayed the entire JSON string with each character having a new line.
here is my JS
$('.partsTextBox').autocomplete({
minLength: 3,
source: function(request, response) {
$.ajax({
url: './PartSearch.ashx',
data: $('.partsTextBox').serialize(),
datatype: 'JSON',
type: 'POST',
success: function(data) {
response($.map(data, function(item) {
return { label: item.partNumber }
}))
}
});
},
select: function(e) {
ptb.value = e;
}
});
Any help anyone can give would be much appreciated. Have edited to include help given by soderslatt
I'm not sure, but shouldn't parts.part be an array ?
http://jsfiddle.net/jfTVL/3/
From the jQuery autocomplete page:
The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.
Which means that if you use "value" instead of "partNumber", you should get want you want.
jquery autocomplete plugin format out have to
{"query":"your_query","suggestions":["suggestions_1","suggestions_2"],"data":[your_data]}}
and use autocomplete that
$('#your_input').autocomplete({
minChars: 2
, serviceUrl: './PartSearch.ashx'
, deferRequestBy: 50
, noCache: true
, params: { }
, onSelect: function(value, data) {
}
, ajaxCallBack: function() {
response($.map(data, function(item) {
return { label: item.partNumber}
}))
}
});
With this code:
function setupRow(event, ui) {
var textbox, // how do i get to the textbox that triggered this? from there
// on i can find these neighbours:
hiddenField = textbox.next(),
select = textbox.parents('tr').find('select');
textbox.val(ui.item.Name);
hiddenField.val(ui.item.Id);
$.each(ui.item.Uoms, function(i, item){
select.append($('<option>' + item + '</option>'));
});
return false;
}
function setupAutoComplete(){
var serviceUrl = "/inventory/items/suggest";
$("input.inputInvItemName").autocomplete({
source: function(request, response) {
$.ajax({
url: serviceUrl,
data: request,
dataType: "json",
success: function(data) {
response($.map(data.InventoryItems, function(item) {
return {
value: item.Name
};
}));
},
select: function(event, ui) {
setupRow(event, ui);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 3,
delay: 500
});
}
everything seems ok. Problem is the select handler never fires, not even the anonymous function that wraps my original delegate setupRow for debugging purposes is ever called.
anyone can see my error?
I also left a question in the comment: how do I get to the textbox that had the autosuggestion. Cannot use id here, because these text boxes are multiples and generated on the fly, interactively. Or is there another way to do the same thing?
Thanks for any help!
OP point of view
var textbox, // how do i get to the textbox that triggered this? from there
// on i can find these neighbours:
My Point of view
have you tried,
var textbox = $(event.target);
or you can do this,
OP point of view
select: function(event, ui) {
setupRow(event, ui);
},
My point of view
select: setupRow;
then
var textbox = this; // just a guess... wait..
anyone can see my error?
I think you forgot to put ';' .
$.ajax({
url: serviceUrl,
data: request,
dataType: "json",
success: function(data) {
response($.map(data.InventoryItems, function(item) {
return {
value: item.Name
}
}));
Or is there another way to do the same thing?
I think u are using the jquery ui autocomplete plugin.If yes, you can retreive like this.
$('.ui-autocomplete-input')
Otherwise, you can set a specific class to those textboxes and access those textbox through that class.
ok, got a step closer by using
inputs.bind("autocompleteselect", setupRow);
now setupRow fires.
Now it seems, that the success callback transforms the data, I get returned.I need to find a way, to both display the right value in the dropdown, without destroying the requests response...
Any ideas?