jQuery UI autocomplete with custom data from Facebook Graph API friends - javascript

i want my facebook graph api /me/friends list in an autocomplete field. I want choose my friend, select one of them end have its ID.
Facebook response with a "data" json object with name and id. Perfect!
Some code:
$(document).ready(function(){
FB.api('/me/friends', function(fbresponse){
$("#input_13").autocomplete({
source : function(request, response){
response($.map(fbresponse.data, function(e){
return{
id : e.id,
name : e.name
}
}))
},
select : function(event, ui){
alert(ui.item.name);
$("#input_13").val(ui.item.name);
$("#input_10").val(ui.item.id);
return false;
}
}).data("autocomplete")._renderItem = function(ul, item){
return $("<li></li>")
.data("item.autocomplete", item)
.append( $("<a></a>").html(item.name) )
.appendTo(ul);
};
});
});
Results is at 90%, when I begin typing, the list of my friends appears but it's order from the first to the end, it's not filtered.
Example:
My list complete is:
marco
massimo
marino
mimmo
simone
sara
sonia
when I begin with "s" should result only
simone
sara
sonia
but the result list does not change.
What's happen?
Thanks a lot.

As your source property is pointing to a function it is called ever the plugin needs the datasource, the problem is: the FB Graph API don't accept a "term" param when searching for friends so it returns always the same data based on your input. What you need is something like this:
var makeItems = function(fbresponse) {
return $.map(fbresponse, function(item) {
return {
label: item.name,
value: item.id,
}
});
};
var setAutoComplete = function(parsed_items) {
$("#input_13").autocomplete({
source : parsed_items,
select : function(event, ui){
alert(ui.item.name);
$("#input_13").val(ui.item.name);
$("#input_10").val(ui.item.id);
return false;
}
}).data("autocomplete")._renderItem = function(ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append( $("<a></a>").html(item.name) )
.appendTo(ul);
};
};
FB.api('/me/friends', function(fbresponse) {
setAutoComplete(makeItems(fbresponse.data));
});
It will make only one request, will get all the friends and set a variable with an array of parsed items so the filter can act in the array.
I hope it help you.

take a look at this code example, its working fine.
http://blogs.microsoft.co.il/blogs/alon_nativ/archive/2011/05/30/search-facebook-friends-with-jquery-autocomplete.aspx

Related

Fix URL to return dropdownlist items with JsonResult - MVC- C#

My js dropdown code:
$(document).ready(function () {
$("#ddDivision").change(function () {
$.get("GetDepartment", { id: $("#ddDivision").val() }, function (data) {
$("#ddDept").empty();
$("#ddDept").append("<option value='Please Select'>Please Select</option>")
$.each(data, function (index, row) {
console.log(row);
$("#ddDept").append("<option value='" + row.Value + "'>" + row.Text + "</option>")
});
});
})
});
The JsonResult that returns the list:
public JsonResult GetDepartment(int id)
{
List<SelectListItem> items = new List<SelectListItem>();
//query to return items
return Json(items, JsonRequestBehavior.AllowGet);
}
The error I get (the dropdown does not populate) but I get this in F12 dev tools:
http://localhost/Home/EditView/GetDepartment?id=2
So the URL is wrong, because its on EditView, it should return GetDepartment list, but it doesnt. How do I fix the URL ?
When I'm on the Index view, it returns the correct URL like Home/GetDepartment - how to fix this when using another view?
Also to mention, I use one controller, HomeController.
There are two ways to fix this problem of urls.
Way 1:
Normally the recommended approach is to use the Url.Action helper method which makes sure to generate the correct url for the specified controller and action like:
$.get('#Url.Action("GetDepartment","Home")', { id: $("#ddDivision").val() }, function (data)
Way 2:
and if the js code is in a separate js file then what we do is use data attributes of html elements like:
<select id="ddlDivision" data-url='#Url.Action("GetDepartment","Home")'>
and then in js what we can do is to use that url from data- attributes like below:
$("#ddDivision").change(function () {
var url = $(this).data("url");
$.get(url , { id: $("#ddDivision").val() }, function (data) {
Hope it gives you idea of either way.

Use multiselect with dynamically generated select

I am trying to use the multiselect plugin I found on here:
How to use Checkbox inside Select Option
The question above is for a <select> with hard coded <options>.
The <select> I am using generates <options> using jQuery and PHP with this function:
function initializeSelect($select, uri, adapt){
$.getJSON( uri, function( data ) {
$select.empty().append($('<option>'));
$.each(data, function(index, item) {
var model = adapt(item);
var $option = $('<option>');
$option.get(0).selected = model.selected;
$option.attr('value', model.value)
.text(model.text)
.appendTo($select);
});
});
};
initializeSelect($('#salesrep'), 'process/getSalesReps.php', function (item) {
return {
value: item.final_sales_rep,
text: item.final_sales_rep
}
});
I have used the above function several times in different projects, as it successfully creates all of the options brought in by the PHP process. Unless requested, I will not show the code for the process. Just know I am indeed retrieving a group of names and displaying them in the dropdown.
Right beneath the function above is where I call the multiselect feature:
$('select[multiple]').multiselect();
$('#salesrep').multiselect({
columns: 1,
placeholder: 'Select Reps'
});
The HTML for the select is as follows:
<select class="form-control" name="salesrep[]" multiple id="salesrep"></select>
Using all of the above, the output looks like this:
Upon inspecting the element, I can see all of the sales reps names. This tells me that the initializeSelect function is working properly.
Therefore I think the issue must have something to do with the multiselect.
Ajax calls are asynchronous. You call multiselect() before the ajax call has had time to complete and therefore the option list is still empty at the point you call the multiselect() function.
Either move the $('#salesrep').multiselect({.. bit to inside the getJSON method or call the multiselect refresh function after the option list has been populated as I am doing here. (Untested.)
function initializeSelect($select, uri, adapt){
$.getJSON( uri, function( data ) {
$select.empty().append($('<option>'));
$.each(data, function(index, item) {
var model = adapt(item);
var $option = $('<option>');
$option.get(0).selected = model.selected;
$option.attr('value', model.value)
.text(model.text)
.appendTo($select);
});
//now that the ajax has completed you can refresh the multiselect:
$select.multiselect('refresh');
});
};
initializeSelect($('#salesrep'), 'process/getSalesReps.php', function (item) {
return {
value: item.final_sales_rep,
text: item.final_sales_rep
}
});
$('select[multiple]').multiselect();
$('#salesrep').multiselect({
columns: 1,
placeholder: 'Select Reps'
});

Input with autocomplete jquery and Odoo rpc call don't show suggestions

I want use the jquery autocomplete for loading data from backend when the user still pressing keys.
I see that site for making autocomplete with ajax call.
Here the code that i'm using but i'm stucked with results.
I don't understand how the autocomplete take back odoo rpc result and show it in the input form
<label class="control-label" for="timesheet_user_id">Employee:
</label>
<input id="employee_name"/>
And jquery autocomplete
var employee_name = $('#employee_name');
employee_name.autocomplete({
source: function (request, response) {
ajax.jsonRpc("/employee_search", "call", {"name": employee_name.val()})
.then(function (data) {
response(data);
console.debug(response);
});
},
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
By console i see that i receive the array of objects but nothing happens on html.
Maybe is wrong the type of data or how i make the rpc call?
Backend function:
#http.route("/employee_search", type="json",
auth="public", website=True)
def employee_search(self, name):
employee_objs = request.env["hr.employee"] \
.sudo().search([("name", "ilike", name)])
if not employee_objs:
return {"fail": True}
suggestions = []
for employee in employee_objs:
employee_vals = {}
employee_vals['value'] = employee.id
employee_vals['data'] = employee.name
suggestions.append(employee_vals)
# make a dict of dicts with employees values
return suggestions
EDIT
Modified into jquery autocomplete the response = data; with
.then(function (data) {
response(data);
console.debug(response);
});
Now the input show two little boxes without text inside.
The received data from rpc call still not shown after input box
EDIT2
the problem is the source:, because if i pass an array of static object i can see them, but with this call nothing happends....where i'm wrong?
employee_name.autocomplete({
source: function (request, response) {
ajax.jsonRpc("/employee_search", "call", {"name": employee_name.val()})
.then(function (data) {
response(data);
console.debug(response);
});
}
});
Data contain the array of values but source don't catch them.
Ok i finally write a code that work for a real time search with suggestions:
Here the JS:
/*Autocomplete that suggest input*/
var serial_number = $('#searchSerial');
serial_number.autocomplete({
minLength: 3,
source: function (request, response) {
ajax.jsonRpc("/serial_search", "call", {"serial": serial_number.val()})
.then(function (data) {
console.debug(data);
if (data.fail) {
// if SN was not found in the db alert the user
// This is non blocking, the user can still compile the form
//alert(_t("Serial Number not found in the system, please fill the form manually"));
serial_number.addClass('error_input');
} else {
serial_number.removeClass('error_input');
response(data);
}
});
},
//If the record return is only one auto select it
response: function (event, ui) {
if (ui.content.length === 1) {
ui.item = ui.content[0];
serial_number.val(ui.item.value);
serial_number.data('ui-autocomplete')._trigger('select', 'autocompleteselect', ui);
serial_number.autocomplete('close');
}
},
select: function (event, ui) {
let brand_id = $("input[name='brand_id']");
let brand_name = $("input[name='brand_name']");
let product_id = $("input[name='product_id']");
let product_name = $("input[name='product_name']");
let serial_number = $("input[name='serial_number']");
brand_id.val(ui.item.brand_id);
brand_name.val(ui.item.brand_name);
product_id.val(ui.item.product_id);
product_name.val(ui.item.product_name);
serial_number.val(ui.item.serial_number);
}
});
The Javascript Code make search when user input at least 3 letters, if only one record match the case, it is auto selected by response:.
The selected: case populate other input field when user select a certain voice into suggestions list.
Here che controller that return suggestions data:
#http.route("/serial_search", type="json",
auth="public", website=True)
def serial_search(self, serial):
"""
Starting from a serial number (portal user input),
serach for the corresponding lot and then search
for product id/name and brand id/name.
Return them to the website form.
"""
serial_domain = [("name", "ilike", serial)]
serial_objs = request.env["stock.production.lot"] \
.sudo().search(serial_domain, limit=10)
if not serial_objs:
return {"fail": True}
suggestions = []
for serial_obj in serial_objs:
serial_vals = {}
serial_vals['data'] = serial_obj.product_id.id
serial_vals['value'] = serial_obj.name
serial_vals['product_id'] = serial_obj.product_id.id
serial_vals['product_name'] = '%s - %s' % (
serial_obj.product_id.default_code, serial_obj.product_id.name)
serial_vals['brand_id'] = serial_obj.product_id.product_brand_id.id
serial_vals['brand_name'] = serial_obj.product_id.product_brand_id.name
serial_vals['serial_number'] = serial_obj.name
suggestions.append(serial_vals)
# make a list of dicts with serial number values
return suggestions

Render html element present inside jquery autocomplete data

I am making use of jQuery autocomplete with remote data source. Remote data contains HTML tags. Sample data is of form:
[
"ABC <span>XYZ</span>",
"PQR <span>LMN</span>",
];
Autocomplete dropdown contain output like
ABC <span>XYZ</span>
PQR <span>LMN</span>
I want HTML tags to get render and dropdown to show output like
ABC XYZ
PQR LMN
http://jsfiddle.net/ac112jmx/2/
You can override it using Custom Display use .autocomplete("instance")._renderItem method.
instance()
Retrieves the autocomplete's instance object. If the element does not have an associated instance, undefined is returned.
_renderItem( ul, item )
Method that controls the creation of each option in the widget's menu. The method must create a new <li> element, append it to the menu, and return it.
Code
$("#tags").autocomplete({
source: availableTags,
select: function (event, ui) {
console.log(ui.item);
$("#tags").val(ui.item.label);
return false;
}
}).autocomplete( "instance" )._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
DEMO
You can use $.parseHTML(str)
var dropdown = $.parseHTML('ABC <span>XYZ</span>');
Check the following example:
$('#wrp').html($.parseHTML('This is a <b>Bold text</b>'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="wrp"></span>

Trying to get Jquery working with dynamic select forms in Rails and Active Admin

I'm trying to update a select box based on another..
In my active admin resource, I did the following just for some test data:
controller do
def getcols
list = new Hash
list = {"OPTION1" => "OPTION1", "OPTION2" => "OPTION2"}
list.to_json
end
end
In active_admin.js I have the following
$('#worksheet_type').change(function() {
$.post("/admin/getmanifestcols/", { ws_type: $(this).val() }, function(data) {
populateDropdown($("#column_0"), data);
});
});
function populateDropdown(select, data) {
 select.html('');
alert('hi');
$.each(data, function(id, option) {
select.append($('<option></option>').val(option.value).html(option.name));
});      
}
The above is working in the sense that when my primary select box is changed, the jquery is called and I even get the alert box of 'hi' to be called. However, it's not replacing the contents of the select box with my test OPTION1 and OPTION2 data.
I think I'm passing in the JSON wrong or something, or it's not being read.
What am i missing?
It looks to me as if you're not properly iterating over the map.
What about:
$.each(data, function(value, name) {
select.append($('<option></option>').val(value).html(name));
});
?

Categories