Here is the code I'm attempting to use (parts pulled from remote json, parts removed from the custom data display):
$(function () {
$("#Field1Text").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
url: "/Main/Users/GetItems",
dataType: "json",
data: {
group: "Default",
query: request.term
}
},
focus: function (event, ui) {
$("#Field1Text").val(ui.item.Description);
return false;
},
select: function (event, ui) {
$("#Field1Text").val(ui.item.Description);
return false;
}
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.data("item.autocomplete", item)
.append("<a><strong>" + item.Description + "</strong><br>" + item.Section + " - " + item.Type + " - " + item.Name + "</a>")
.appendTo(ul);
};
});
The data pulls back fine, but the render item function never fires. I've scrapped the render item version and used success: inside of source and it looked like this:
success: function (data) {
response($.map(data, function (ul, item) {
return $("<li>")
.data("item.autocomplete", item)
.append("<a><strong>" + item.Description + "</strong><br>" + item.Section + " - " + item.Type + " - " + item.Name + "</a>")
.appendTo(ul);
}));
}
I used firebug and I was able to hit a breakpoint at the response section: if I looked at the data in data, it looked like:
[ Object { ...data... }, Object { ...data... }]
If I set a breakpoint at the .data line of the success section, I see that ul is one of the objects ( looks like " Object { ... data ... }")
the item element is 0 at this point, and when I attempt to render the <a> tags, it comes out as Undefined on all of the properties (understandable, looks to be treating the item object as an int).
How do I get that component to handle properly?
edit: sorry, I wanted to add a jsFiddle per the suggestion in the comments but had family stuff going on.
http://jsfiddle.net/EYj8v/2/
I commented the code that is similar to what we use at work. Unfortunately, the web app is an internal one with a database that isn't connected to the outside world so I can't use live data. The testResults object is what I saw in the success: section's data element.
I was actually able to get the success section to fire, but I don't believe I'm using jQuery UI/Autocomplete correctly (at least my assumptions) as I was able to look at ul.Properties and see real data. Appending the items worked with bogus data, but when I attempted to copy and paste the success block into the render item, all of the data was undefined. Nor could I find a one-to-one mapping at that stage (ul was the element on the page, item was just [li]).
Related
Hi I have implemented search bar in my application and I am using autocomplete plugin for that. On the select event of that after selecting an item from list I am redirecting it to another page with the custom Url I have provided But it is not working on another page because the custon url is getting appeneded with the url I have already given. So kindly give me solution for that.
I have tried replacing url with window.locarion.replace("url") but it is not helping
$("#txtsearch").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Action("Search", "Product")",
type: "POST",
dataType: "json",
data: {
search: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.ModelName,
value: item.ModelName,
type:item.ID
};
}))
}
})
},
select: function (event, ui) {
debugger;
//var url = 'Product/Review/' + ui.item.value + '-' + ui.item.type
window.location.replace('Product/Review/'+ ui.item.value +'-' + ui.item.type);
// window.location.href = url;
//window.location.href = ('Product/Review/' + ui.item.value + '-' + ui.item.type);
}
});
I want some code so that on select event previous url will get removed and I will be able to redirect the user to the custom url I have given in the select event
Try adding a forwarding slash at the starting, like this:
window.location.replace('/Product/Review/'+ ui.item.value +'-' + ui.item.type);
In my Grails project (version 2.2.1) I'm using the following Javascript code in two different GSP pages.
<g:javascript>
$(document).ready(function() {
$.ajax({
type: "GET",
url: "/medicalOfficeManager/Patient/getAllPatients",
dataType: "json",
success : function(response) {
//Create a map.
var data =
$.map(response, function(item){
console.log("id: " + item.id);
console.log("name: " + item.surname + " "+ item.name);
return{
id: item.id,
value: item.surname + " " + item.name
}
});
$("#patient_textField").autocomplete({
source: data,
select: function (event, ui){
console.log("selected id:" + ui.item.id);
console.log("selected name:" + ui.item.value);
//when a country is selected(ie: type China and press enter),
//change the value of hidden field to the country's id.
$('#patient_id').val(ui.item.id);
console.log("patient value = "+ $('#patient_id').val());
}
});
}
});
});
</g:javascript>
In one GSP everything works as expected, in another one, looking at Javascript console, I have the following error:
$(...).autocomplete is not a function
I've read this discussion, but it does not work for me.
Any suggestion?
EDIT: I've noticed that the only difference betweeen pages is that, in the not working one, it is loaded the bundle-bundle_core_head.js, but I don't see where it is loaded in gsp page...
EDIT2: there was a component loading in other gsp that includes an earlier version of JQuery and JQuery UI, but I need that component because, if I comment it, another field that allows me to choose date and time does not work. Is it possible to use both?
The autocomplete function is likely provided by a jQuery plugin that you are including in one page, but not the other. View the source of each page and compare the <script> elements in each.
I recently came across the Yify-torrents api at YifyTorrentAPI and just thought let's give it a try with jquery and create a little own application. I used the following code to retrieve the upcomming movies list which worked.
$.getJSON("https://yts.re/api/upcoming.json", function(data) {
$.each(data, function(item, value) {
console.log(value.MovieTitle + ' ' + value.ImdbLink);
});
});
on the other side when I tried to get all the movies list using the following request I just got undefined in the console.
$.getJSON("https://yts.re/api/list.json", function (data) {
$.each(data, function (item, value) {
console.log(value.MovieTitleClean + ' ' + value.ImdbLink);
});
});
I am sharing the Fiddle in which I have wrote the code. Any help will be appreciated. Thanks
The second ajax call is returning movies in a MoviesList object so you need to iterate on data.MovieList not data.
JSON:
{
"MovieCount":4921,
"MovieList":
[{
"MovieID":"5372",
"State":"OK",
"MovieUrl":"https:\/\/yts.re\/movie\/Gun_Woman_2014_1080p",
"MovieTitle":"Gun Woman (2014) 1080p","MovieTitleClean":"Gun Woman",
"MovieYear":"2014",
"DateUploaded":"2014-06-30 00:10:03",
"DateUploadedEpoch":1404043803,
"Quality":"1080p",
"CoverImage":"https:\/\/static.yts.re\/attachments\/Gun_Woman_2014_1080p\/poster_med.jpg",
"ImdbCode":"tt3141912",
"ImdbLink":"http:\/\/www.imdb.com\/title\/tt3141912\/",
"Size":"1.24 GB",
"SizeByte":"1335275815",
"MovieRating":"8.2",
"Genre":"Action",
"Uploader":"OTTO",
"UploaderUID":"310615",
"Downloaded":"35173",
"TorrentSeeds":"20",
"TorrentPeers":"24497",
"TorrentUrl":"https:\/\/yts.re\/download\/start\/777FD07DAD285CB06846CAFD97600B07F2CC88B3.torrent",
"TorrentHash":"777fd07dad285cb06846cafd97600b07f2cc88b3",
"TorrentMagnetUrl":"magnet:?xt=urn:btih:777fd07dad285cb06846cafd97600b07f2cc88b3&dn=Gun+Woman&tr=http:\/\/exodus.desync.com:6969\/announce&tr=udp:\/\/tracker.openbittorrent.com:80\/announce&tr=udp:\/\/open.demonii.com:1337\/announce&tr=udp:\/\/exodus.desync.com:6969\/announce&tr=udp:\/\/tracker.yify-torrents.com\/announce"
}]
}
do like this:
$.getJSON("https://yts.re/api/list.json", function (data) {
console.log("Getting all the movies");
// console.log(data)
$.each(data.MovieList, function (item, value) {
console.log(value.MovieTitleClean + ' ' + value.ImdbLink);
});
});
UPDATED FIDDLE
the last 5 days I fall into despair. I am forced to use an ajax interface for getting usernames in an autocomplete input. This works fine but I also want to add some user-avatars. Adding an avatar-image to autocomplete search results works fine too but only by typing avatar-path directly without ajax response to _renderItem() like
//see complete code below
var inner_html = '<img src="img/avatar-123.png" /><span>' + item.label + '</span>';
I want to manipulate the first ajax JSON-result:
{"data":[{"label": "Simon",
"value":{ "shareType":0,
"shareWith":"Simon"
}
}],
"status":"success"}
in something like this:
{"data":[{ "label": "Simon",
"value":{ "shareType":0,
"shareWith":"Simon"
"avatar":"img/avatar-123.png"
}
}],
"status":"success"}
But adding a new avatar-Object to the json-Object don't work :( Do you have any ideas what I am doing wrong?
$("#search").autocomplete({
minLength: 2,
focus : function(event, focused) {
event.defaultPrevented();
},
source: function(search, response) {
$.when(
//get usernames
$.get(OC.filePath('core', 'ajax', 'share.php'), {
fetch : 'getShareWith',
search : search.term
})
/*example result:
{"data":[{ "label": "Simon",
"value":{ "shareType":0,
"shareWith":"Simon"
}
}],
"status":"success"}*/
//result of first ajax goes in the next round
).then(function(content) {
$.each(content.data, function(i, item) {
//get avatars for usernames
$.get(OC.filePath('ownchat', 'ajax', 'get_avatar.php'), {
username: content.data[i].label
}, function(img) {
//firebug says everthing is working till here
//now I want to add a new avatar-Object to the json-Object
content.data[i].value.avatar = img;
});
});
//the following code-result is empty
//alert(content.data[0].value.avatar);
//but calling
//setTimeout(function(){
// response(content.data);
// },2000);
//in place of the following line, it works sometimes
response(content.data);
});
}/*,
manipulate search result
response: function (e, ui) {
This do not work too :(
for(i in ui.content) {
$.get(OC.filePath('ownchat', 'ajax', 'get_avatar.php'), {
user_id: ui.content[i].label
}, function(img) {
ui.content[i].avatar.push = { avatar: img };
});
}
}*/
}).data("ui-autocomplete")._renderItem = function (ul, item) {
var inner_html = '<img src="'+ item.value.avatar +'" /><span>' + item.label + '</span>';
return $("<li></li>")
.data("item.autocomplete", item)
.append(inner_html)
.appendTo(ul);
};
Sorry for the long text but I hope you can help.
Greetings André
Once i also needed this type of requirement in which username and picture was needed to show, after trying alot, what i came up was build my own custom autocomplete, and it works great i reuse it whenever it is required, you can see it here:
http://developmentpassion.blogspot.com/2013/12/facebook-and-linkedin-like-searching.html
I want to send json data from my controller to my view when a specific action happens.
I used this on controller to send the data
[HttpGet]
public JsonResult JSONGetParking(int buildingID){
return this.Json(
new
{
Result = (from obj in db.Parkings.Where(p => p.buildingID == buildingID) select new { ID = obj.ID, Name = obj.note })
}
, JsonRequestBehavior.AllowGet
);
}
it works very good
on my script i used this:
FloorScript.js
$(document).ready(function () {
$('#buildingID').change(function () {
alert("what is not");
$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
alert("afd");
var items = " ";
$.each(data, function (obx, oby) {
items += "<option value='" + oby.ID + "'>" + oby.Name + "</option>";
});
$('#parkingID').html(items);
});
});
});
I have opened google chrome and I can see the request and the response like this:
i can see the two text that i alerted
However, on my selector, i just see undefined value
Html
<div id="editor-label">
<select id="parkingID" name="parkingID"></select>
</div>
I have added the jquery in this
#section scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/FloorScript.js");
}
You're not looping on the correct variable.
You did this:
$.each(data, function (obx, oby) {
whereas you should do this:
$.each(data.Result, function (obx, oby) {
This is pretty visible in the Google Chrome screenshot you provided. As you can see the returned JSON has a property called Result which is the collection whereas you were looping over the data variable which is not an array - it's just a javascript object that has a property called Result which is the array you wanna be looping through.
Also I'd replace:
$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
with:
$.getJSON('JSONGetParking', { buildingID: $('#buildingID').val() }, function (data) {
and of course get rid of this hardcoded url over there and use an url helper to generate it, on the dropdown as an HTML5 data-* attribute:
#Html.DropDownListFor(
x => x.BuildingId,
Model.Buildings,
new {
id = "buildingID",
data_url = Url.Action("JSONGetParking")
}
)
and then inside the change event you can trivially easy retrieve this url and avoid hardcoding it (and of course taking the risk of breaking your code when you deploy it in IIS in a virtual directory or simply change the routing pattern of your application):
$('#buildingID').change(function () {
var url = $(this).data('url');
$.getJSON(url, { buildingID: $('#buildingID').val() }, function (data) {
Alright, now the initial mess is tidied up.
use data.Result in your each loop
$(document).ready(function () {
$('#buildingID').change(function () {
alert("what is not");
$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
alert("afd");
var items = " ";
$.each(data.Result, function (obx, oby) {
items += "<option value='" + oby.ID + "'>" + oby.Name + "</option>";
});
$('#parkingID').html(items);
});
});
});
Hope this helps...