why jquery autocomplete doesnt work on https (secure pages)? - jquery-ui

I am trying to make jquery autocomplete to be work on https (secured pages) pages but its not showing any dropdown.
I searched on this issue and found that its security issue.
can any one tell me how to turn on this autocomplete dropdown on https pages.
here is my code to jquery autocomplete :
function zipAutoCompletet(prefix) {
jQuery("#" + prefix + "_zip").autocomplete({
source: function (request, response) {
jQuery.ajax({
url: "http://ws.geonames.org/postalCodeSearchJSON",
dataType: "jsonp",
data: {
style: "full",
maxRows: 12,
postalcode_startsWith: request.term
},
success: function (data) {
response(jQuery.map(data.postalCodes, function (item) {
return {
label: item.placeName + (item.adminCode1 ? ", " + item.adminCode1 : "") + ", " + item.postalCode + ", " + item.countryCode,
value: item.postalCode
}
}));
jQuery('.ui-autocomplete').css('width', '188px');
}
});
},
minLength: 2,
select: function (event, ui) {
var myString = new String(ui.item.label);
var address = myString.split(',')
jQuery('#' + prefix + '_city').val(address[0]);
jQuery('#' + prefix + '_city').addClass('activated');
jQuery('#' + prefix + '_city').trigger('change');
jQuery('#' + prefix + '_city').parents('.row').removeClass('error-row')
jQuery('#' + prefix + '_city').parents('.row').addClass('ok-row')
var countryCode = address[3] ? address[3] : address[2]
countryCode = jQuery.trim(countryCode);
var countryName = jQuery('#' + prefix + '_country option[value="' + jQuery.trim(countryCode) + '"]').text()
jQuery('#countryContainer .jqTransformSelectWrapper span').html(countryName)
jQuery('#countryContainer .jqTransformSelectWrapper').addClass('selected-jqtranform');
jQuery('#' + prefix + '_country').parents('.row').addClass('ok-row')
jQuery('#' + prefix + '_country').parents('.row').removeClass('error-row')
jQuery('#' + prefix + '_country').val(jQuery.trim(countryCode))
var stateCode = address[2] ? address[1] : '';
stateCode = jQuery.trim(stateCode)
if (countryCode == 'US') {
var base = base_url;
base = base.replace("https", "http");
jQuery.ajax({
url: base + "/getStateName",
dataType: "jsonp",
data: {
stateCode: stateCode
},
success: function (data) {
stateName = data
jQuery('#jc_state').val(stateName);
jQuery('#jc_state').addClass('activated');
jQuery('#jc_state').parents('.row').removeClass('error-row')
jQuery('#jc_state').parents('.row').addClass('ok-row')
jQuery('#jc_state').trigger('change');
formValidate();
}
});
} else {
stateName = stateCode
jQuery('#jc_state').val(stateName);
jQuery('#jc_state').addClass('activated');
jQuery('#jc_state').parents('.row').removeClass('error-row')
jQuery('#jc_state').parents('.row').addClass('ok-row')
jQuery('#jc_state').trigger('change');
formValidate();
}
jQuery('#' + prefix + '_zip').parents('.row').addClass('ok-row')
jQuery('#' + prefix + '_zip').parents('.row').removeClass('error-row');
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
},
change: function (event, ui) {
if (ui.item === null) {
jQuery("#" + prefix + "_zip").parents('.row').removeClass('ok-row');
jQuery("#" + prefix + "_zip").parents('.row').addClass('error-row');
$("#" + prefix + "_zip").val('');
}
}
});
}
I am using above code for zipcode field.This code works fine on non-https pages it works fine but when I tried it with https pages it doesnt shows.
any solutions are welcome.

As I looked into the service provider they are supporting jsonp and the following sample worked
$("input").autocomplete({
source: function (request, response) {
$.getJSON("http://ws.geonames.org/postalCodeSearchJSON?callback=?",
{ 'postalcode_startsWith': request.term, maxRows: 12, style: "full" },
function(data) {
if(data.postalCodes){
var x = $.map(data.postalCodes, function(v, i){
console.log(v)
return {
label: v.placeName + ' - ' + v.postalCode,
v: v.postalCode
}
});
response(x);
}
}
);
}
});
Demo: Fiddle

Related

Jquery Autocomplete error menuselect and menufocus cannot read property value undefined

$('.searchName').autocomplete({
source: function(req, res){
$.ajax({
url: "{{ route('airportSearch') }}",
dataType: "json",
type: "GET",
data: req,
beforeSend: function() {
$('#iconMaps').hide();
$('#loadingMaps').show();
},
success: function (data){
$('#iconMaps').show();
$('#loadingMaps').hide();
res(data);
console.log(data)
},
error: function(err){
$('#iconMaps').show();
$('#loadingMaps').hide();
}
});
}
}).data('ui-autocomplete')._renderItem = function(ul, item) {
return $('<li>')
.data('ui-autocomplete', item)
.append('<span><b>' + item.label + '</b></span><br><span>' + item.value + '</span>')
.appendTo(ul);
}
this my code, i have problem if selected list have error:
Cannot read property 'value' of undefined.
How to resolve this error?
I had a similar issue after updating JQuery version and fixed it applying few changes in data(), like bellow:
.data('uiAutocomplete')._renderItem = function(ul, item) {
return $('<li>')
.data('ui-autocomplete-item', item)
.append('<span><b>' + item.label + '</b></span><br><span>' + item.value + '</span>')
.appendTo(ul);

Autocomplete not showing suggestion list when triggered second time

I have autocomplete with two sources. When an item is selected after search from first source, if certain conditions are met, the second search is forced. This brings back results - I can see them writing into console but the list of suggestions will not show up unless "keypress" is made. I tried to automate this with forcing the .ui-list to show and with forcing "keypress" events but to no avail... has anybody got any experience and advice on this? Thanks.
$(document).ready(function () {
var stopSearch = false;
var sel = "";
var finished = false;
$('#txtLiveDept').autocomplete({
source: function (request, response) {
console.log("stopSearch" + stopSearch);
if (stopSearch == false) {
console.log("first ajax");
$.ajax({
url: '/en-gb/LiveDepartures/CombinedAjax',
data: "{ inputTerm: '" + request.term + "'}",
//dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
autoFocus: true,
success: function (data) {
console.log(data.Locations);
console.log(data.ServiceResponses);
if (data)
var resp1 = data.Locations;
var resp2 = data.ServiceResponses;
var dataF = resp2.concat(resp1);
console.log(dataF);
response($.map(dataF, function (item) {
console.log("item" + item.FullText);
var label = "";
if (item.FullText == undefined) {
label = item.ServiceNumber + ", " + item.Description;
}
else {
label = item.FullText;
}
return {
Label: label,
FullText: item.FullText,
Category: item.Category,
Latitude: item.Latitude,
Longitude: item.Longitude,
value: label,
StopLabel: item.StopLabel,
ServiceId: item.ServiceId
}
}));
failure: function err(response) {
console.log("error: " + response.d);
}
},
});
}
else if (stopSearch == true) {
console.log("second ajax");
$.ajax({
url: '/en-gb/LiveDepartures/GetStops',
data: "{ serviceId: '" + sel + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
autoFocus: true,
success: function (data) {
if (data) {
response($.map(data, function (item) {
console.log("item" + item.Name + item.StopLabel);
$("#txtLiveDept").val("");
$(".ui-menu").show();
console.log("just before");
return {
label: item.Name + ", " + item.StopLabel,
FullText: item.FullText,
Category: item.Category,
Latitude: item.Latitude,
Longitude: item.Longitude,
value: item.Name + ", " + item.StopLabel,
StopLabel: item.StopLabel,
ServiceId: item.ServiceId
};
}));
}
},
});
}
},
select: function (e, selected) {
console.log("selected:" + selected.item.ServiceId);
if (selected.item.ServiceId != undefined) {
console.log("in third");
sel = selected.item.ServiceId;
var item = selected.item.ServiceId;
console.log("third item" + item);
stopSearch = true;
console.log("finished" + finished);
if (finished == false) {
$("#txtLiveDept").autocomplete("search", item);
}
else {
alert("hey");
}
}
},
minLength: 0
});
});
Please consider the following code.
$(function() {
var stopSearch = false;
var sel = "";
var finished = false;
function getCombined(q) {
var results;
$.ajax({
url: '/en-gb/LiveDepartures/CombinedAjax',
data: {
inputTerm: q
},
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
console.log(data.Locations);
console.log(data.ServiceResponses);
if (data.length) {
var dataF = data.Locations.concat(data.ServiceResponses);
console.log(dataF);
results = $.map(dataF, function(item) {
console.log("item" + item.FullText);
var label = "";
if (item.FullText == undefined) {
label = item.ServiceNumber + ", " + item.Description;
} else {
label = item.FullText;
}
return {
Label: label,
FullText: item.FullText,
Category: item.Category,
Latitude: item.Latitude,
Longitude: item.Longitude,
value: label,
StopLabel: item.StopLabel,
ServiceId: item.ServiceId
}
});
}
},
failure: function err(response) {
console.log("error: " + response.d);
}
});
return results;
}
function getStops(q) {
var results;
$.ajax({
url: '/en-gb/LiveDepartures/GetStops',
data: {
serviceId: q
},
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data.length) {
results = $.map(data, function(item) {
console.log("item" + item.Name + item.StopLabel);
$("#txtLiveDept").val("");
$(".ui-menu").show();
console.log("just before");
return {
label: item.Name + ", " + item.StopLabel,
FullText: item.FullText,
Category: item.Category,
Latitude: item.Latitude,
Longitude: item.Longitude,
value: item.Name + ", " + item.StopLabel,
StopLabel: item.StopLabel,
ServiceId: item.ServiceId
};
});
}
}
});
return results;
}
$('#txtLiveDept').autocomplete({
autoFocus: true,
source: function(request, response) {
console.log("stopSearch", stopSearch);
if (stopSearch) {
console.log("second ajax");
response(getStops(sel));
} else {
console.log("first ajax");
response(getCombined(request.term));
}
},
select: function(e, selected) {
console.log("selected:" + selected.item.ServiceId);
if (selected.item.ServiceId != undefined) {
console.log("in third");
sel = selected.item.ServiceId;
var item = selected.item.ServiceId;
console.log("third item" + item);
stopSearch = true;
console.log("finished" + finished);
if (finished == false) {
$("#txtLiveDept").autocomplete("search", item);
} else {
alert("hey");
}
}
return false;
},
minLength: 0
});
$('#txtLiveDept').focus(function(){
$(this).autocomplete("search");
});
});

Passing data from Ajax to Rails controller

I'm having a little problem with my rails app.
I am trying to pull a random name from an array and pass it into my rails controller and into a method.
This is my AJAX:
var artists = [array with some names]
randomA = {}
var randomArtist = artists[Math.floor(Math.random()*artists.length)];
randomA['a_name'] = randomArtist.toString();
$.ajax({
url: "/songs_echowrap/" + randomA.a_name,
dataType: "json"
}).success(function(data) {
Do Stuff
}
});
});
Here is my routes:
get 'songs_echowrap/:artist_name' => 'users#get_echonest'
Here is my controller:
def get_echonest
foo = params[:artist_name]
#rec = Echowrap.playlist_basic(:artist => params[:artist_name] , :results => 25)
render json: #rec
end
The param is 'undefined' when i run a binding.pry in my terminal.
Do like this in ajax,
$.ajax({
type: "GET",
url: "/songs_echowrap?artist_name=" + randomA.a_name,
datavalue: 'html',
}).success(function(data) {
Do Stuff
}
});
});
In routes,
get 'songs_echowrap' => 'users#get_echonest'
In controller,
def get_echonest
foo = params[:artist_name]
#rec = Echowrap.playlist_basic(:artist => params[:artist_name] , :results => 25)
render json: #rec
end
Within your ajax call you should specify the method (in this case, looks like a GET) and the data required:
$.ajax({
type: "GET",
url: "/songs_echowrap/" + randomA.a_name,
data: randomA.a_name,
}).success(function(data) {
Do Stuff
}
});
});
Try This:
small change with your code, it will work add data varidable in your ajax call like this:
var artists = [array with some names]
randomA = {}
var randomArtist = artists[Math.floor(Math.random()*artists.length)];
randomA['a_name'] = randomArtist.toString();
$.ajax({
url: "/songs_echowrap/" + randomA.a_name,
dataType: "json",
data: {artist_name: randomA.a_name }
}).success(function(data) {
Do Stuff
}
});
});
Sorry, I am relatively new to Javascript and I should have been more clear with my code.
I realized that one of my variables was in the wrong scope so it kept returning as undefined.
I was making two AJAX requests, and I thought i could return the value from the first and pass it through to the second. This question helped me understand my problem: How do I return the response from an asynchronous call?
this is my javascript now:
$('span').on('click', function(){
$('#s_title').empty();
$("#playlist_title").empty();
$("#viito_list").empty();
var p_title = $(this).html();
$("#playlist_title").append(p_title);
var id = $(this).data("id");
var artistsList = []
$.ajax({
url: "/songs/"+id,
dataType: "json",
success: successCallback
})
function successCallback(data){
for(var i = 0; i < data.length; i++){
function msToTime(duration) {
var seconds = parseInt((duration/1000)%60),
minutes = parseInt((duration/(1000*60))%60)
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return minutes + ":" + seconds ;
}
artistsList.push(data[i].artists[0].name);
$("#s_title").append("<tr> <td>" + data[i].name + "</td>" + "<td>" + data[i].artists[0].name + "</td>" + "<td>" + msToTime(data[i].duration_ms) + "</td>" + "<td><span class='glyphicon glyphicon-remove song-select'></span>" + "</td> </tr>")
}
randomArtist = artistsList[Math.floor(Math.random()*artistsList.length)];
getWeird(randomArtist)
}
function getWeird(rando){
$.ajax({
type: "GET",
url: "/songs_echowrap?artist_name=" + rando,
dataType: "json"
}).success(function(data) {
$("viito_list").empty();
for(var i = 0; i < data.length; i++){
$("#viito_list").append("<tr> <td>" + data[i].title + "</td>" + "<td>" + data[i].artist_name + "</td> </tr>")
}
});
}
});

Select2 nested json parsing not working Rails3

I'm trying to make select2 working with my ajax loaded json data with nested attributes.
I wanna get something like this http://ivaynberg.github.io/select2/#multi.
eaxmple json:
[{
id: 1,
name: "GroupName",
users: [{id: 1, name: 'UserName'}, {id: 2, name: 'SecondUser}]
}]
On the site they use <optgroup label="GroupName"><option value="1">UserName</opyion></optgroup> and getting the right result.
In my case it displays nesting properly, but I can select only GroupName, but I need to select nested userName and make GrouoName unselectable, only gor informational purposes.
code:
$('#user_tokens').select2({
placeholder: "Search for a user",
minimumInputLength: 0,
tags: true,
multiple: true,
ajax: {
url: "messages/users_data.json",
dataType: 'json',
quietMillis: 100,
data: function(search, page) {
return {
q: search,
per: 3,
page: page
};
},
results: function(data, page) {
return {
results: data,
};
}
},
formatResult: formatResult,
formatSelection: formatSelection,
dropdownCssClass: "bigdrop"
});
formatResult:
var formatUserResult = function(data) {
var optgroup = "";
var users = "";
if (data.name !== undefined) {
data.users.forEach(function(e) {
users += "<li class='select2-results-dept-1 select2-result select2-result- selectable'>" +
"<div class='select2-result-label'>" +
"<span class='select2-match'></span>"+
e.firstname +
"</div>" +
"</li>";
});
optgroup += "<div class='select2-result-label'>" +
"<span class='select2-match'></span>" +
data.name + "</div>" +
'<ul class="select2-result-sub">' + users + '</ul>';
}
return optgroup;
}
The problem is that optgroup must have class: 'select2-result-unselectable'
Dunno what to do with it.

Jquery autocomplete Select not working

i want to select the Autocomplete box item list . but it is not working . i have write this code to get the item. whenever i use self._renderItemData = function (ul, item) this function customized way the selection stops and when i comment this function my code works fine . please help me to know where am i wrong. i have used jquery ui 1.9 to write the code.
$(document).ready(function () {
var term = "";
var type = "";
var key = "";
$("#searchTextBox").autocomplete({
minLength: 2,
autoFocus: true,
source: function (request, response) {
$.ajax({
url: "../CustomHandlers/SearchHandler.ashx",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: { term: request.term },
success: function (data) {
if (!data || data.length == 0) {
response([{
label: "noMatched",
hcount:0,
type: "noResult",
key: "noResult"
}]);
}
else {
response($.map(data, function(item) {
return {
label: item.label,
hcount:item.record,
type: item.type,
key: item.key
}
}))
}
}
});
$.ui.autocomplete.prototype._renderMenu=function (ul, items) {
var self = this;
currentType = "";
$.each(items, function (index, item) {
if (item.type != currentType) {
ul.append("<li class='ui-autocomplete-type'>" + item.type + "</li>");
currentType = item.type;
}
self._renderItemData(ul, item);
});
self._renderItemData = function (ul, item) {
var searchhtml = "<a class='autocomplitList'>" + item.label + "<span>" + "(" + item.hcount + ") " + "</span>" + "</a>";
return $("<li></li>")
.data("item.autocomplete", item)
.append(searchhtml)
.appendTo(ul);
};
}
}
, select: function (event, ui)
{
term = ui.item.label;
type = ui.item.type;
key = ui.item.key;
// ui.item.option.selected = true;
// $("#searchTextBox").val(ui.item.label);
// return false;
//var selectedObj = ui.item.key;
// alert("Selected: " + selectedObj);
}
,open: function (event, ui) {
//event.addClass("nodis");
}
,close: function () {
// event.removeClass("nodis")
this._trigger("close");
}
});
Try this
$(document).ready(function() {
var term = "";
var type = "";
var key = "";
$.ui.autocomplete.prototype._renderMenu = function(ul, items) {
var self = this;
currentType = "";
$.each(items, function(index, item) {
if (item.type != currentType) {
ul.append("<li class='ui-autocomplete-type'>"
+ item.type + "</li>");
currentType = item.type;
}
self._renderItemData(ul, item);
});
self._renderItemData = function(ul, item) {
var searchhtml = "<a class='autocomplitList'>" + item.label
+ "<span>" + "(" + item.hcount + ") " + "</span>" + "</a>";
return $("<li></li>").data("item.autocomplete", item)
.append(searchhtml).appendTo(ul);
};
}
$("#searchTextBox").autocomplete({
minLength : 2,
autoFocus : true,
source : function(request, response) {
response([{
label : "Value 1",
hcount : 0,
type : "t1",
key : "v1"
}, {
label : "Value 2",
hcount : 0,
type : "t1",
key : "v2"
}, {
label : "Value 3",
hcount : 0,
type : "t2",
key : "v3"
}, {
label : "Value 4",
hcount : 0,
type : "t3",
key : "v4"
}]);
}
,
select : function(event, ui) {
term = ui.item.label;
type = ui.item.type;
key = ui.item.key;
// ui.item.option.selected = true;
// $("#searchTextBox").val(ui.item.label);
// return false;
// var selectedObj = ui.item.key;
// alert("Selected: " + selectedObj);
},
open : function(event, ui) {
// event.addClass("nodis");
},
close : function() {
// event.removeClass("nodis")
this._trigger("close");
}
});
$("#searchTextBox").data('autocomplete')._renderMenu = function(ul, items) {
var that = this;
var currentType = "";
$.each(items, function(index, item) {
if (item.type != currentType) {
ul.append("<li class='ui-autocomplete-type'>"
+ item.type + "</li>");
currentType = item.type;
}
$("<li></li>").addClass('newp').append($("<a></a>")
.text(item.label)).appendTo(ul).data(
"ui-autocomplete-item", item);;
});
}
});
Demo: Fiddle

Resources