Input field cache issues with multiple selections on Select2 in Firefox - ruby-on-rails

Currently attempting to implement Select2 in my rails app so a user can send messages to multiple users, I adapted the remote data example code on the site for my app as follows:
$("#shareCurrentInput").select2({
placeholder: "Search for a user",
width: "350px",
multiple: true,
minimumInputLength: 3,
ajax: {
url: "search.json",
dataType: 'json',
data: function (term, page) {
return {
search: term
};
},
results: function (data, page) {
return {results: data};
}
},
formatResult: userFormatResult,
formatSelection: userFormatSelection,
escapeMarkup: function (m) { return m; }
});
function userFormatResult(user) {
var markup = "<table class='user-result'><tr>";
if (user.uid !== undefined ) {
markup += "<td class='user-image'><img src='http://graph.facebook.com/" + user.uid + "/picture?width=50&height=50'/></td>";
}
markup += "<td class='user-info'><div class='user-title'>" + user.name + "</div>";
markup += "</td></tr></table>";
return markup;
}
function userFormatSelection(user) {
return user.name;
}
This works as I intend it to in Safari, but in Firefox, I believe due to the fact that by default the browser caches input values from session to session, it causes issues when refreshing the page and attempting to select users. Is there a way to prevent Firefox from caching this in the code (i.e. without asking the user to turn off caching in their browser setting)? Or is there another reason this code isn't working in Safari?
I've tried using this code to disable autocomplete through jQuery, and there doesn't seem to be a CSS method to disable form autocomplete. There also seem to be issues with disabling autocomplete in Chrome. Is there an optimum cross-browser solution? Autocomplete is off by default in the input field in Select2, and the input is not part of a form, so this solution does not seem possible.
EDIT: As per this page, the issue is only when I refresh the page, if I press enter in the address bar then there is no issue.

Just added this code:
$('#shareCurrentInput').val('');
Seems to work even on refresh in Firefox.

If similar issue is happening with page refresh/reload using jQuery, try
document.location.reload(true);
instead of document.location.reload();
Details: https://developer.mozilla.org/en-US/docs/Web/API/Location/reload

Related

Preload page into turbolinks transition cache

I'm using turbolinks to simulate a "single-page" app. The app is acceptably quick once pages are cached, however the first clicks are too slow. Is there a way to pre-fill the transition cache by loading some pages in the background?
I'm going to be looking into hacking into the page cache, but wondering if anyone has done this before.
(If this seems unusual, well, just trust that I'm doing this for good reason. Turbolinks gets nearly the performance of a far more complex implementation and overall I'm quite happy with it.)
UPDATE: So it seems like this SHOULD be relatively easy by simply adding entries to the pageCache of Turbolinks, something like:
$.ajax({
url: url,
dataType: 'html',
success: function(data) {
var dom = $(data);
Turbolinks.pageCache[url] = {
...
}
}
});
however it doesn't seem possible to construct a body element in javascript, which is required. Without out that, it doesn't seem like I can't construct the object that is stored in the cache without the browser first rendering it.
Any ideas beyond hacking more into Turbolinks?
UPDATE 2: There was the further problem that pageCache is hidden by a closure, so hacking Turbolinks is necessary. I have a solution that I'm testing that leverages iFrames - seems to be working.
First Hack Turbolinks to allow access to pageCache, the end of your turbolinks.js.coffee should look like this.
#Turbolinks = {
visit,
pagesCached,
pageCache,
enableTransitionCache,
enableProgressBar,
allowLinkExtensions: Link.allowExtensions,
supported: browserSupportsTurbolinks,
EVENTS: clone(EVENTS)
}
Then implement a fetch function. This is what you were thinking about, we can use DOMParser to convert string into DOM object.
function preFetch(url) {
$.ajax({
url: url,
dataType: 'html'
}).done(function(data) {
var key = App.Helper.getCurrentDomain() + url;
var parser = new DOMParser();
var doc = parser.parseFromString(data, "text/html");
Turbolinks.pageCache[key] = {
url: url,
body: doc.body,
title: doc.title,
positionY: window.pageYOffset,
positionX: window.pageXOffset,
cachedAt: new Date().getTime(),
transitionCacheDisabled: doc.querySelector('[data-no-transition-cache]') != null
};
});
};
Usage:
$(function() {
preFetch('/link1'); // fetch link1 into transition cache
preFetch('/link2'); // fetch link2 into transition cache
});

jquery mobile 1.4 not updating content on page transition

From the index page, a user clicks a navigation link, the data attribute is passed via ajax, the data is retrieved from the server but the content is not being updated on the new page.
Been stuck for hours, really appreciate any help!
js
$('a.navLink').on('click', function() {
var cat = $(this).data("cat");
console.log(cat);
$.ajax({
url: 'scripts/categoryGet.php',
type: 'POST',
dataType: "json",
data: {'cat': cat},
success: function(data) {
var title = data[0][0],
description = data[0][1];
console.log(title);
$('#categoryTitle').html(title);
$('#categoryTitle').trigger("refresh");
$('#categoryDescription').html(description);
$('#categoryDescription').trigger("refresh");
}
});
});
Im getting the correct responses back on both console logs, so I know the works, but neither divs categoryTitle or categoryDescription are being updated. I've tried .trigger('refresh'), .trigger('updatelayout') but no luck!
This was not intended to be an answer (but I can't comment yet.. (weird SO rules)
You should specify in the question description that the above code IS working, that your problem occurs WHEN your playing back and forth on that page/code aka, using the JQM ajax navigation.
From what I understood in the above comment, you're probably "stacking" the ajax function every time you return to the page, thus getting weird results, if nothing at all.
Is your example code wrapped into something ? If not, (assuming you use JQM v1.4) you should consider wrapping it into $( 'body' ).on( 'pagecontainercreate', function( event, ui ) {... which I'm trying to figure out myself how to best play with..
Simple solution to prevent stacking the ajax definition would be to create/use a control var, here is a way to do so:
var navLinkCatchClick = {
loaded: false,
launchAjax: function(){
if ( !this.loaded ){
this.ajaxCall();
}
},
ajaxCall: function(){
// paste you example code here..
this.loaded = true;
}
}
navLinkCatchClick.launchAjax();

JQuery Mobile & URL Parameters white flash on reload

I am using query mobile for a phonegap application, I am passing through parameters through the url to the next page.
For example:
main.html?id=1, menu.html?id=2 etc
To allow this I have to turn ajaxEnabled to false to allow it to pass through the information I need. In doing so I am unable to use transitions from page to page which means I get a white flash as the page reloads.
I am generating these links dynamically.
$.ajax({
url: 'URLTO WEBSERVER',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var list = '<li><a href="menu.html?idcat='+item.id_cat+'">'+item.category_cat+'</li>'
output.append(list);
});
},
error: function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
output.text('There was an error loading the data.')
}
});
Is there a solution?
you can use method jquery serialize data for your paramater.
via changePage method in jquery
I hope solved :D
I think he is concerned about the "white plash page" that happens after the request is completed from server and then he calls changePage.
He is not worried about how to send parameters to server etc. This is assuming all that is working fine.

jQuery Mobile Secure Pages

I'm developing a jquery mobile site that is only available to users that are logged in.
I have a function that checks a server for their logged in status:
function checkLogin() {
$(function () {
$.getJSON(root_url + 'manageUsers/checklogin/?callback=?', null,
function (data) {
if (data.logged == 'false') {
$("#index_Container").html("<h2>Login Required</h2></div><p>We've noticed you're not logged in, please login to use this app.</p><p><a href='login.html' data-role='button'>Click here to login</a></p>").trigger('create');
$.mobile.changePage('login.html');
} else {
$(".logged_in").text(data.username);
$(".logged_in").addClass('logout');
$(".header_div").trigger('create');
}
});
});
}
I can't seem to figure out how to implement this so everytime the index page is loaded and any other page loads this is fired prior to rendering anything else on the page. Currently, the page will load and show the HTML, then do $.mobile.changePage('login.html'):
EDIT: If anyone has any ideas on how to implement this in a better way I'd love to know, every page in the app requires the user to be logged in.
In order to have this function run every time you load anew page, you will need to bind it to the pagebeforeload event, and potentially cancel the user navigation if it does not validate the login.
$( document ).bind( "pagebeforeshow", function( event, data ){
event.preventDefault(); //prevents usual load of page
checkLogin(data);
});
You will have to make changes to checkLogin, notably because as the page does not exist yet, so you cannot make changes to the DOM. You can see an quick and dirty example in this fiddle, giving hints as to how do it considering the asynchronous nature of your call.

jQuery UI Autocomplete - IE6 lockup

Before you say it, I know, IE6 is dead and it smells like it's dead. However my client has a closed network, all their machines are run only IE6, so that 100% of my user base :/
I'm using jQuery UI and the autocomplete widget, it performs well in Firefox however on IE6, even for a small list of items (here 5, returned by json with an item and a description) it's locking up the browser when I mouse over them. Applying the css seems like it may be the cause.
$( "#searchTest" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "index.pl",
dataType: "json",
data: {
term: request.term
},
success: function( data ) {
response( $.map( data.items, function( item ) {
return {
label: item.id + ' - ' + item.label,
value: item.id
}
}));
}
});
},
minLength: 2
});
I can even kind of replicate the problems in IE6 using the online demos, albeit to a much lesser extent, it's just slow it doesn't hang up the browser.
If anyone can make any suggestions for improving performance in IE6 I'd be very happy to hear them. I'm using the default style sheet from the Themeroller. Thanks
Doh! I was using a plugin to add round corners to IE6: http://dillerdesign.com/experiment/DD_roundies/
I commented this out and it's working way better! The plugin in question is now EOL (my bad for not checking this). The client will have to live with a functional system, but no round corners till they change browser versions.

Resources