I am currently working on a Spring mvc project in which I am using the jQuery autocomplete plugin to load data from a JSON file rendered from the server.
$('#searchTerm').autocomplete({
serviceUrl: '${ctx}/search/searchAutocomplete',
paramName: "parameterName",
delimiter: ",",
transformResult: function(response) {
return {
suggestions: $.map($.parseJSON(response), function(item) {
return {
value: item.userName + " , " + item.userId + ", " +
item.pathToImageFile , data: item
};
})
};
},
onSelect: function (suggestion) {
$(this).val(suggestion.data.userName);
console.log(suggestion.data.userId);
console.log(suggestion.data.pathToImageFile);
window.location.href = "${ctx}/userPage?
userID="+suggestion.data.userId;
}
});
This code works as expected. I am able to show the data of the suggestions in the suggestions list, and I am able to redirect to another page when selecting the item.
My inquiry is, how do I use the data from item.pathToImageFile to generate an image of a profile picture whithin the suggestions list? Similar to how facebook shows the profile pictures of users or groups when you search.
I went over the following similar topics here:
jQuery UI - Formatting the autocomplete results. Add image possible?
Jquery UI autocomplete - images IN the results overlay, not outside like the demo
How to change rendering of dropdown in jquery ui autocomplete attached to a class?
However I can't seem to apply the accepted answers in my code. In plain html and javascript, I know the syntax for each suggestion item should look something like this:
'<img src="'+ suggestion.data.pathToImageFile + '"/>'
'<p>' +suggestion.data.userName + '</p>'
I just can't seem to figure out the configurations and built in methods of the autocomplete plugin. The documentation does not help at all. Hope someone can help me out. Thanks
You need to add .data("ui-autocomplete")._renderItem = function (ul, item) {
in my AJAX response the item.label already contains the needed HTML code with the correct format (I don't use images, but other formatting)
$('#searchTerm').autocomplete({
serviceUrl: '${ctx}/search/searchAutocomplete',
paramName: "parameterName",
delimiter: ","
/* This is the part to be implemennted */
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
You need to adjust the code and your AJAX response, but I think you can take it from here...
I can't help with the jquery.autocomplete plugin, but if you can't get it to work the Select2 plugin features this functionality and it is well documented on their examples page on github here (look in the "Data Sources -> Loading remote data", section).
Perhaps you might get some insight/inspiration from there? Hope that's helpful!
Related
I'm trying to add entries to a dropdown list which I have defined in my .jade file as below.
extends layout
block content
script(src='http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js')
script(src='/javascripts/addsystem.js')
h1= title
p Testing
select#allSystems
And my Ajax method looks like the following:
var select = $('#allSystems');
console.log("Runing script")
$.ajax({
url: '/submit/getAllSystems',
dataType:'JSON',
success:function(data){
$.each(test.system, function(key, val) {
select.append('<option id="' + val.id + '">' + val.name + '</option>');
})
}
});
The Ajax script is located the JS file which is included in the Jade file. (Jquery is also included in the Jade file).
Everything seems to be working fine, except for the append. I.e. the console logs show good data all the way and when printing the select object in the Ajax script the browser recognizes it as a HTML element.
When printing the running "console.log(select);", Firefox console shows the following:
Object { context: HTMLDocument → submit, selector: "#allSystems" }
Any idea what I'm doing wrong?
Jade is a templating language that has to be compiled and executed with the data in order to render HTML. JQuery will not automatically do that for you, which is why your commented-out attempt at select.append failed.
Building the HTML yourself works (though it makes some ugly code and I still dislike string concatenations). However, when you did that you changed to .appendTo, which is going to try and take your select object and append it to the option, which I don't think is what you want.
give this a shot:
select.append('<option id="' + val.id + '">' + val.name + '</option>');
If that doesn't work, then there's something up with your selector that gets you the select variable.
* EDIT *
I notice in your Jade that you are loading your scripts before the rest of the DOM. IF the contents of addsystem.js are as you describe, then you're fetching the data and trying to append it to a DOM node that doesn't exist yet. Try wrapping it like so:
$(function(){ /** your code **/ })
Which is a shorthands to jQuery's methods for doing stuff after the DOM is fully loaded.
I am running jQuery with in this Javascript function. My problem is that after successful completion, I get a message which I display in an alert dialog.
My message string is something like that "Avinash|Ajay|Rahul..." This is dynamic. Now I want to show these names in a dialog list.
function showRemarks(number) {
$.ajax({
url : 'PrintRemarks.jsp',
data : 'COURSE_CODE=' + "<%=course_code%>" + '&TYPE=' + "<%=course_type%>" + '&NUMBER=' + number,
type : 'post',
success : function(msg) {
alert(msg);
}
});
}
Unless you don't use gui elements from browser, there is no way to show an (HTML) list in this element. As far as can see you use jquery so there should be also be possible to use jqueryui.
In case you want really really use the element from browser you can format the output text. You just have to use '\t' -a tabsign- and '\n' - a linebreak. Here an example:
var msg = "A list:\n\t- Number one\n\t- Number two\n\t\t\t- Number two-one";
alert(msg);
I doubt you don't want this...
You can show HTML in jQuery Dialog. Please check the link: http://jqueryui.com/dialog/#modal-form.
So you can add a div in your body and then as per your above example you can place the list in that container DIV. After that you have initialize tha jQuery dialog.
I have made a code in javascript/jquery which populates a division with tweets of a specific handle.
$.getJSON("http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+ handle + "&count=" + noOfTweets + "&include_rts=true&callback=?", function(data) {
//some code
});
Here is the code to display the tweets
Json.parse(data);
$.each(data, function(i, tweet) {
var buttonString = '<br/><a onclick="retweet('+tweet.id+')">Retweet</a>'
+'<a onclick="favorite('+tweet.id+')">Favorite</a>';
$("#tweets").append($("<li/>").html(tweet.text+" <span class='tweetTime'>--a moment ago.</span>")+buttonString);
}
I now want to add retweet and favorite buttons to the tweets.
The twitter api for the above functions require a post request, but jquery doesn't have any .postJSON() function
https://dev.twitter.com/docs/api/1/post/statuses/retweet/:id
and
https://dev.twitter.com/docs/api/1/post/favorites/create/:id
so what should my retweet and favorite functions contain?
Some help please.
jQuery has a function to make POST requests - jQuery.post()
Used web intents instead.
Not preferable, but not bad.
A newbie question,
I am trying to use Freebase Suggest as a tagging resource for my Django project. I want to extract item name, type and id. For example, as you can see in the screenshot, I want to extract the name 'Pearl Jam' ,its id '/en/pearl_jam', and the type 'band'.
How can I post this data to my view?
Using the function below I can only create links to the tags.
$(function(){
$("#myinput").suggest().bind("fb-select", function(e, data) {
$('#myinput').val(''); // clear the input
$('#returnValueOfFreebase').append(''+ data.name +' ')})
});
You already have the name and the ID from data.name and data.id. You can also access the notable type from your callback function by using data['n:type'].name like this:
$(function(){
$("#myinput").suggest().bind("fb-select", function(e, data) {
$('#myinput').val(''); // clear the input
$('#returnValueOfFreebase').append(''+ data.name +' (' + data['n:type'].name + ')')})
});
If you want to capture this data and post it back to your web app, you can create some hidden inputs and set their value from the Freebase suggest callback. Like this:
<input id="notable_type" name="notable_type" type="hidden" />
$("#myinput").suggest().bind("fb-select", function(e, data) {
$("#notable_type").val(data['n:type'].id);
});
New Api use data['notable'] instead of data['n:type']
I know very little (none) JavaScript, or much about using API's. However I would like to display some hotel reviews on my webiste made available over the qype.com API. However I'm struggling with being able to manage this.
This is the code I have so far:
$(document).ready( function() {
$.getJSON( "http://api.yelp.com/business_review_search?term=hilton%20metropole&location=B26%203QJ&ywsid=APIKEY Removed",
function(data) {
$.each( data.businesses, function(i,businesses) {
content = '<p>' + businesses.reviews.text_excerpt + '</p>';
content = '<p>' + businesses.reviews.date + '</p>';
$(content).appendTo("#review");
} );
}
);
} );
I have a div in the body called review where I want to display the text.
Any advice greatly received.
JSON can be found at http://api.yelp.com/business_review_search?term=hilton%20metropole&location=B26%203QJ&ywsid=lOoGGbkYpVmTvxHlWGT2Lw
Also, I have multiple businesses on the same page, how would I make use of this multiple times on the same page, but output the data in different locations?
Update: Ah, I see your error now. businesses.reviews is an array (each business can have more than one review) so you have to loop over each business and each business' reviews.
i had to change some things to get it to run in my test bed, but you can see a sample of this code running here: http://bit.ly/4mTxPp
yelp currently support JSONP calls so you can change your code to:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function showData(data) {
$.each(data.businesses, function(i,business){
// extra loop
$.each(business.reviews, function(i,review){
var content = '<p>' + review.text_excerpt + '</p>';
content += '<p>' +review.date + '</p>';
$(content).appendTo('#review');
});
});
}
$(document).ready(function(){
// note the use of the "callback" parameter
writeScriptTag( "http://api.yelp.com/business_review_search?"+
"term=hilton%20metropole"+
"&location=B26%203QJ"+
"&ywsid=lOoGGbkYpVmTvxHlWGT2Lw"+
"&callback=showData"); // <- callback
});
function writeScriptTag(path) {
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", path);
document.body.appendChild(fileref);
}
</script>
Do you get an error in Firebug using this code? What happens exactly?
I expect this problem is caused by the fact that you're trying to do a cross-domain request which is not allowed. Normally you'll want to do this kind of data gathering on your back-end, but you can use an alternative such as JSONP to do the same.
Take a look at jQuery's documentation on this stuff and it should be clear what's going on.
Also, as a side note: In your callback you have content = which is ok but not ideal. Assigning to content like this will create a variable in the global scope which you do not want. In this case it probably wont cause an issue but say you have 2 of these requests going at once, the second assignment could easily step on the first causing hard-to-debug weirdness. Best to just always create variables with var.
If data.businesses is an array, I would assume that data.businesses[x].reviews is also an array. This code loops the businesses as well as the reviews for each business. It also gets rid of the content variable by appending straight to the #review div.
$.each(data.businesses, function(i,business){
$.each(business.reveiws, function(r,review){
$("#review").append(
'<p>' + review.text_excerpt + '</p>'
).append(
'<p>' + review.date + '</p>'
);
});
});
I think you can specify JSONP with your $.getJSON method by adding "callback=?" to the url parameters.
As of jQuery 1.2, you can load JSON
data located on another domain if you
specify a JSONP callback, which can be
done like so: "myurl?callback=?"
$.getJSON("http://api.yelp.com/business_review_search?term=hilton%20metropole&location=B26%203QJ&ywsid=APIKEY Removed&callback=?",
function(data){
...
});
The problem is that you are making a cross domain request, which is not allowed for security purposes. Either you will have to make a proxy script on your domain (like for example in php) and call yelp from that or fetch the data completely on the server side.
I assume you must be experiencing part of your data (which you are supposed to see) disappearing. I think you must edit your code to:
content = '<p>' + businesses.reviews.text_excerpt + '</p>';
content += '<p>' + businesses.reviews.date + '</p>';
Hope this helps...