I can't get the item selected from the result set of jQuery UI Autocomplete to appear in the textbox after clicking on it, however i can navigate through them with keyboard and select with enter key. Here is my code:
$(document).ready(function () {
$('#t1').autocomplete({
source: function (request, response) {
// prepare url : for example '/api/artistapi?query=sonu
var autocompleteUrl = '/api/KeywordAutoComplete/' + request.term;
$.ajax({
url: autocompleteUrl,
type: 'GET',
cache: false,
dataType: 'json',
success: function (json) {
// call autocomplete callback method with results
response($.map(json, function (data, id) {
return {
label: data.KeyText
};
}));
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
console.log('some error occured', textStatus, errorThrown);
}
});
},
minLength: 3,
select: function (event, ui) {
$('#autocomplete-textbox').val(ui.item.label);
return false;
}
});
I went trough some similar questions on Stackoverflow but none of them solved my issue. Some have suggested that the problem happens if in your header section you load more than one JQuery-UI Libraries. Here is my my header:
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
Eliminating any of these lines from my header did not help. Thank you all
Related
I'm hoping I can get some help on working with jquery easy autocomplete. I am trying to create a url function that calls an html page that has a javascript xmlrpc function, and returns a list of name in json format. All I get in the web console is:WARNING: Fail to load response data.
Query Page:
<html>
<script src="./js/jquery-3.1.1.min.js" type="text/javascript" ></script>
<script src="./js/jquery.xmlrpc.js" type="text/javascript" ></script>
<body>
<p id="display"></p>
</body>
<script>
$(document).ready(function() {
var url = "https://url.to.my.api/nameapi";
$.xmlrpc({
url: url,
methodName: 'API.FullNameQuery',
success: function(response, status, jqXHR) {
var resp = response + '';
document.getElementById('display').innerHTML = resp;
},
error: function(jqXHR, status, error) { console.log("Error getting information:" + error) }
});
});
</script>
</html>
Easy Autocomplete page:
<html>
<script src="./js/jquery-3.1.1.min.js" type="text/javascript" ></script>
<script src="./js/jquery.easy-autocomplete.min.js"></script>
<link rel="stylesheet" href="css/easy-autocomplete.min.css">
<link rel="stylesheet" href="css/easy-autocomplete.themes.min.css">
<body>
<input id="inputOne" placeholder="Full Name" />
<input id="inputTwo" placeholder="netID" />
</body>
<script>
$(document).ready(function() {
var resp;
var options = {
url: function(phrase) {
return phrase !== "" ?
"https://url.to.my.api/get-people.html" :
"https://url.to.my.api/get-people.html";
},
getValue: "fullName",
ajaxSettings: {
dataType: "json"
},
requestDelay: 300,
theme: "blue-light",
list: {
maxNumberOfElements: 200,
match: {
enabled: true
}
}
};
$("#inputOne").easyAutocomplete(options);
});
</script>
</html>
This is hosted on an IIS server, and I can't use php like the examples show for easy autocomplete. The page returns proper json as I have validated it, so I'm a little confused what it doesn't like it.
I had kind of the same problem if I understand correctly.
I wanted to load an array of data only once, which is not how easy autocomplete works. If you use the URL it will do requests once you type letters.
1) : Create an Easy AutoComplete function that load the settings (re-usable is dope) :
function autoComplete(data_src) {
return {
data: loadManufacturer(data_src),
getValue: "name",
theme: "bootstrap",
list: {
match: {
enabled: true
},
showAnimation: {
type: "fade", //normal|slide|fade
time: 200,
callback: function () {}
},
hideAnimation: {
type: "slide", //normal|slide|fade
time: 200,
callback: function () {}
}
}
};
}
2) : Store the datas in a var
function loadManufacturer(url) {
var tmp = null;
$.ajax({
'async': false,
'type': "GET",
'global': false,
'dataType': 'json',
'url': url,
'success': function (data) {
tmp = data;
}
});
return tmp;
}
3) Call your function in an input :
$("#search_product_manufacturer").easyAutocomplete(
autoComplete(
$("#search_product_manufacturer").attr('data-src')
)
);
You are using Duckduckgo search of easyAutocomplete.
Change your code as follows:
var options = {
.....
ajaxSettings: {
data: {
dataType: "jsonp"
}
},
.....
}
for other Ajax setting, read Ajax settings guide
I a have a Bootstrap Typeahead function, what I want to customize a little bit. If the user clicks on any of the items in the result dropdown list, the user would be redirected to one subpage. The typeahead function is working great, the dropdown list is populated without any error, this is one example what is return from the php file:
[{"name":"TEXT-ONE","url":"\/textone-postfix"},{"name":"TEXT-TWO","url":"\/texttwo-postfix"},{"name":"TEXT-THREE"
,"url":"\/textthree-postfix"}]
The idea is, that the "name" attribute is displayed to the user and after click, it's redirects to the "url" attribute.
The problem is that right now after I click on ANY of the items I get this error (Firefox Firebug console output):
TypeError: ui is undefined
This is my jQuery function and before that the .js imports:
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="/bootstrap/js/ie10-viewport-bug-workaround.js"></script>
<script src="/bootstrap/js/bootstrap3-typeahead.js"></script>
<script type="text/javascript">
$(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;
}
});
});
});
</script>
</body>
Can someone help me please, what's the problem here?
Thank you very much!
updater function was the solution:
$(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
},
updater: function (item) {
window.location.href = item.url
},
});
});
});
I'm trying to get the remote using json from one php page,the JSON data:
[{"id":"0","name":"ABC"},{"id":"1","name":"DEF I"},{"id":"2","name":"GHI"}]
and the script is like this:
$(document).ready(function() {
$('#test').select2({
minimumInputLength: 1,
placeholder: 'Search',
ajax: {
dataType: "json",
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
term: term
};
},
type: 'GET',
results: function (data) {
return {results: data};
}
},
formatResult: function(data) {
return "<div class='select2-user-result'>" + data.name + "</div>";
},
formatSelection: function(data) {
return data.name;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"name":elementText});
}
});
});
It works fine but it always reads the database whenever I typed one new character to search
. So i decided to use the another way (retrieve all data at first time and use select2 to search it):
$(document).ready(function() {
$("#test").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0; }).length===0) {
return {id:term, text:term};}
},
multiple: false,
data: [{"id":"0","text":"ABC"},{"id":"1","text":"DEF I"},{"id":"2","text":"GHI"}]
});
});
But the problem is how can I pass a request to data_json.php and retrieve data from it?
Say
data: $.ajax({
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
};
}
dataType: "json",
success: function(data){
return data
}
}
But its not working, can anyone help?
Thanks
Why did you move away from your original code?
minimumInputLength: 1
Increase this and the search won't be called on the first character typed. Setting it to 3 for example will ensure the ajax call isn't made (and the database therefore not queried) until after the 3rd character is entered.
if I understood your question correctly you have data_json.php generating the options for select2 and you would like to load all of them once instead of having select2 run an ajax query each time the user inputs one or more characters in the search.
This is how I solved it in a similar case.
HTML:
<span id="mySelect"></span>
Javascript:
$(document).ready(function () {
$.ajax('/path/to/data_json.php', {
error: function (xhr, status, error) {
console.log(error);
},
success: function (response, status, xhr) {
$("#mySelect").select2({
data: response
});
}
});
});
I've found that the above does not work if you create a <select> element instead of a <span>.
I have two pieces of code, first of all I have my code which toggles open a div with an included close button:
http://jsfiddle.net/spadez/uhEgG/27/
$(document).ready(function () {
$('#country').click(function () {
$("#country_slide").slideToggle();
});
$('#close').click(function (e) {
e.preventDefault();
$('#country_slide').slideToggle();
});
});
Then I also have my Ajax code which is designed to fire when the div has been opened:
$(function () {
$('#country_link').on('click', function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
$('.loader').show();
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
// $("#country_slide").hide('fast');
// alert('request failed');
},
complete: function () {
$('.loader').hide();
},
});
return false;
});
});
What I am stuck with now is, how do I make the ajax only execute when the div is being opened? Because I am working with a toggle and close button it seems difficult to work out what the click is doing, whether it is opening it or closing it.
I guess my options are to have some kind of flag or alternatively have some "if" code, so if class is equal to .hidden then do not execute. I haven't been able to integrate either of these solutions and I am unsure if either of them is the proper way to achieve this.
Include the check as part of your slide function:
$("#country_slide").slideToggle(function() {
if ($(this).is(":visible")) {
alert("im visible!");
}
});
Demo: http://jsfiddle.net/tymeJV/uhEgG/28/
if($("#country_slide").is(":visible"))
//call ajax
This code adds data to the element, to check if it's already loaded next time you click on it.
Currently I am not able to test it, so it may contain errors.
$(function () {
$('#country_link').on('click', function (e) {
// Prevent from following the link, if there is some sort of error in
// the code before 'return false' it would still follow the link.
e.preventDefault();
// Get $link because 'this' is something else in the ajax request.
var $link = $(this);
// Exit if the data is loaded already
if ($link.data('loaded') === true)
return false;
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
$('.loader').show();
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
// If successful, bind 'loaded' in the data
$link.data('loaded', true)
},
error: function (xhr, textStatus, errorThrown) {
// $("#country_slide").hide('fast');
// alert('request failed');
},
complete: function () {
$('.loader').hide();
},
});
});
});
I am new to jquery and coding in general. This is what I am trying to do:
When a link is clicked, expand the #country_slide div
Show "loading" text
If ajax is successful, put the contents of an html file into the div
Otherwise alert an error and close the div
This is the code I now have:
http://jsfiddle.net/spadez/n9nVs/5/
window.onload = function () {
var a = document.getElementById("country_link");
a.onclick = function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$("#country_slide").show();
$("#country_slide").val('<p>Loading</p>')
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$("#country_slide").hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
}
}
When the link is clicked, I never see the loading text in the box. Please can someone tell me where I have gone wrong here? Also if anyone can offer any words of advice about my first jquery script I would really appreciate it.
Your anchor's id is country, not country_link. So:
var a = document.getElementById("country");
or just use jQuery's id selector:
var a = $("#country");
or even better directly chain:
$(function() {
$('#country').click(function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$("#country_slide").show();
$("#country_slide").html('<p>Loading</p>')
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$("#country_slide").hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
}
});
Notice that I have used the $(document).ready function instead of window.onload. Also I have replaced the onclick event subscription with jQuery's click function. If you are using jQuery it would be better to take full advantage of it.
Working jsFiddle Demo
You don't have any country_link element in your page.
Instead of using window.onload you can use DOM ready.
Attach click handler by jQuery with .on() method.
The .val() method is for <input />. For other elements, use .html() instead.
// DOM ready instead of window.onload
$(function () {
// attach click handler by jQuery instead of onclick
$('#country').on('click', function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$("#country_slide").show();
// val() method is for <input />
// use html() instead
$("#country_slide").html('<p>Loading</p>')
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$("#country_slide").hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
});
});
References:
.html() - jQuery API Documentation
.on() - jQuery API Documentation
.val() - jQuery API Documentation
jQuery( callback ) - jQuery API Documentation
On the fiddle you have
<a href="#" id="country">
Where it should be:
<a href="#" id="country_link">
or change the JS to be
var a = document.getElementById("country");
Because there is no element with an ID country_link
document.getElementById() returns null if the element isn't found
document.getElementById('country').onclick = ...; //should work
In JavaScript, null is a special primitive and you cannot add properties to primitive types.
You have to add an element with id=country_link and the this code will work as NOX said. I have tried that in jsfiddle. try it using
$("#country").click(function(){
// your code goes here
})
that will works.
document.getElementById("country_link"); shall be replaced by document.getElementById("country"); as "country_link" is not the id of any <a> tag in the mark up.
If you are using jQuery library you may handle event like-
$(document).on("click","a",function(){
//ajax stuff
});
Updated Your jsfiddle Code. Just check. its going to failure method. In your workspace you should have the test.html returning the actual data. Thanks.
Don't use plain JS if you already have jQuery (it will be easier for you):
;$(document).ready(function(){
$(country_link).click(function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$(country_slide).show();
$(country_slide).val('<p>Loading</p>');
},
success: function (data, textStatus) {
$(country_slide).html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$(country_slide).hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
});
});