I have a <div> containing a <video> element, and a <ul>. Clicking on an element in the <ul> causes an AJAX call to update the contents of the <div>. On my first attempt, the first video would load correctly, but then clicking on a different link would only load the poster, but not the controls. After some Googling, I found the solution to that, which leaves me with the following AJAX call:
$.ajax({
// each video has its own unique ID
url: "/Video?id=' + id,
success: function (data) {
$('#containing_div').html(data);
// necessary to re-load video player controls
_V_('video_' + id, { "controls": true, "autoplay": false, "preload": "auto" });
}
});
Adding the initialization call to _V_ seemed to help matters somewhat: now when I switch videos, the "play" control appears as expected, and I can play a video. However, once I do, when I switch to a different video, the controls are now gone again. Furthermore, there are weird random errors: if I change videos a few times, suddenly the controls disappear for no apparent reason. Also, occasionally, a second after I switch to a new video, the video poster disappears completely.
Clearly, some "magic" happens in Video.js on page load that is not being triggered by the AJAX call, but I haven't been able to figure out what that is. There's nothing wrong with the <video> tags because initially they were all in-line in the page, and they were being hidden/shown by changing their opacity, and that worked fine (the reason I want to move to AJAX is the page size is huge when all the videos are loaded in-line).
It turns out the solution was to call .destroy() (an undocumented API function) on the outgoing video:
if( currentVideoId ) {
_V('video_' + currentVideoId).destroy();
}
$.ajax({
// each video has its own unique ID
url: "/Video?id=' + id,
success: function (data) {
$('#containing_div').html(data);
// necessary to re-load video player controls
_V_('video_' + id, { "controls": true, "autoplay": false, "preload": "auto" });
currentVideoId = id;
}
});
Related
Got an issue with safari loading old youtube videos when back button is clicked. I have tried adding onunload="" (mentioned here Preventing cache on back-button in Safari 5) to the body tag but it doesn't work in this case.
Is there any way to prevent safari loading from cache on a certain page?
Your problem is caused by back-forward cache. It is supposed to save complete state of page when user navigates away. When user navigates back with back button page can be loaded from cache very quickly. This is different from normal cache which only caches HTML code.
When page is loaded for bfcache onload event wont be triggered. Instead you can check the persisted property of the onpageshow event. It is set to false on initial page load. When page is loaded from bfcache it is set to true.
Kludgish solution is to force a reload when page is loaded from bfcache.
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
If you are using jQuery then do:
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
window.location.reload()
}
});
All of those answer are a bit of the hack. In modern browsers (safari) only on onpageshow solution work,
window.onpageshow = function (event) {
if (event.persisted) {
window.location.reload();
}
};
but on slow devices sometimes you will see for a split second previous cached view before it will be reloaded. Proper way to deal with this problem is to set properly Cache-Control on the server response to one bellow
'Cache-Control', 'no-cache, max-age=0, must-revalidate, no-store'
Yes the Safari browser does not handle back/foreward button cache the same like Firefox and Chrome does. Specially iframes like vimeo or youtube videos are cached hardly although there is a new iframe.src.
I found three ways to handle this. Choose the best for your case.
Solutions tested on Firefox 53 and Safari 10.1
1. Detect if user is using the back/foreward button, then reload whole page or reload only the cached iframes by replacing the src
if (!!window.performance && window.performance.navigation.type === 2) {
// value 2 means "The page was accessed by navigating into the history"
console.log('Reloading');
//window.location.reload(); // reload whole page
$('iframe').attr('src', function (i, val) { return val; }); // reload only iframes
}
2. reload whole page if page is cached
window.onpageshow = function (event) {
if (event.persisted) {
window.location.reload();
}
};
3. remove the page from history so users can't visit the page again by back/forward buttons
$(function () {
//replace() does not keep the originating page in the session history,
document.location.replace("/Exercises#nocache"); // clear the last entry in the history and redirect to new url
});
You can use an anchor, and watch the value of the document's location href;
Start off with http://acme.co/, append something to the location, like '#b';
So, now your URL is http://acme.co/#b, when a person hits the back button, it goes back to http://acme.co, and the interval check function sees the lack of the hash tag we set, clears the interval, and loads the referring URL with a time-stamp appended to it.
There are some side-effects, but I'll leave you to figure those out ;)
<script>
document.location.hash = "#b";
var referrer = document.referrer;
// setup an interval to watch for the removal of the hash tag
var hashcheck = setInterval(function(){
if(document.location.hash!="#b") {
// clear the interval
clearInterval(hashCheck);
var ticks = new Date().getTime();
// load the referring page with a timestamp at the end to avoid caching
document.location.href.replace(referrer+'?'+ticks);
}
},100);
</script>
This is untested but it should work with minimal tweaking.
The behavior is related to Safari's Back/Forward cache. You can learn about it on the relevant Apple documentation: http://web.archive.org/web/20070612072521/http://developer.apple.com/internet/safari/faq.html#anchor5
Apple's own fix suggestion is to add an empty iframe on your page:
<iframe style="height:0px;width:0px;visibility:hidden" src="about:blank">
this frame prevents back forward cache
</iframe>
(The previous accepted answer seems valid too, just wanted to chip in documentation and another potential fix)
I had the same issue with using 3 different anchor links to the next page. When coming back from the next page and choosing a different anchor the link did not change.
so I had
House 1
View House 2
View House 3
Changed to
House 1
View House 2
View House 3
Also used for safety:
// Javascript
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
// JQuery
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
window.location.reload()
}
});
None of the solutions found online to unload, reload and reload(true) singularily didn't work. Hope this helps someone with the same situation.
First of all insert field in your code:
<input id="reloadValue" type="hidden" name="reloadValue" value="" />
then run jQuery:
jQuery(document).ready(function()
{
var d = new Date();
d = d.getTime();
if (jQuery('#reloadValue').val().length == 0)
{
jQuery('#reloadValue').val(d);
jQuery('body').show();
}
else
{
jQuery('#reloadValue').val('');
location.reload();
}
});
There are many ways to disable the bfcache. The easiest one is to set an 'unload' handler. I think it was a huge mistake to make 'unload' and 'beforeunload' handlers disable the bfcache, but that's what they did (if you want to have one of those handlers and still make the bfcache work, you can remove the beforeunload handler inside the beforeunload handler).
window.addEventListener('unload', function() {})
Read more here:
https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/1.5/Using_Firefox_1.5_caching
I'm fairly new to Javascript and Leaflet, so apologies if I'm missing something obvious here, but...
I'm trying to use Leaflet to overlay a series of lines and points on a map, and I want to open a sidebar whenever the user clicks on one of those lines or points. Since the content of the sidebar will vary depending on which line or point the user clicks, I'm trying to use onEachFeature for the mouse event, since I'll then be able to display information related to the appropriate feature.
The problem, though, is that onEachFeature never seems to be called. Here's my code:
function sortAndVisualizeNetwork(){
$.ajax({
url: "d3/networkdata.json",
async: false,
dataType: "json",
success: function(data){
edges = L.geoJson(data, {
filter: function(feature){
if (includeFeature(feature)){
visualizeFeature(feature);
}
},
onEachFeature: function(feature, layer){
layer.on("click", function(e){
//write stuff to sidebar depending on the feature
sidebar.show();
});
}
})
}
})
}
I've tried replacing the layer.on code with simple alerts, none of which appear, so I know onEachFeature isn't being called. The functions within filter work just fine, though.
I'm wondering if this is related to the fact that this is all nested within a synchronous ajax call?
I have a little problem with my script here. For some reason, it doesn't enable the #-tags and I don't know why. I created this javascript using the help of this tutorial. (The loading of the pages works well with no problems at all.)
Could someone please look it over and tell me why it doesn't work?
var default_content="";
$(document).ready(function(){ //executed after the page has loaded
checkURL(); //check if the URL has a reference to a page and load it
$('ul li a').click(function (e){ //traverse through all our navigation links..
checkURL(this.hash); //.. and assign them a new onclick event, using their own hash as a parameter (#page1 for example)
});
setInterval("checkURL()",250); //check for a change in the URL every 250 ms to detect if the history buttons have been used
});
var lasturl=""; //here we store the current URL hash
function checkURL(hash)
{
if(!hash) hash=window.location.hash; //if no parameter is provided, use the hash value from the current address
if(hash != lasturl) // if the hash value has changed
{
lasturl=hash; //update the current hash
loadPage(hash); // and load the new page
}
}
function loadPage(url) //the function that loads pages via AJAX
{
// Instead of stripping off #page, only
// strip off the # to use the rest of the URL
url=url.replace('#','');
$('#loading').css('visibility','visible'); //show the rotating gif animation
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0) //if no errors
{
$('#content').html(msg); //load the returned html into pageContet
} $('#loading').css('visibility','hidden');//and hide the rotating gif
}
});
}
You can simplify this immensely by adding a function to listen to the hashchange event, like this:
$(window).on("hashchange", function() {
loadPage(window.location.hash);
});
This way you don't need to deal with timers or overriding click events on anchors.
You also don't need to keep track of lasthash since the hashchange even will only fire when the hash changes.
I am using Asp.Net MVC3, for a project.
In one of the page, I am using MS Charts. In View I have a Image which shows the chart as follows:
<img src="#Url.Action("RenderCharts", "Home", new
{
XAxisColor = ViewBag.XAxisColor,
YAxisColor = ViewBag.YAxisColor,
})" alt="Charts" runat="server" />
I have 2 CheckBoxes, which is used to change Chart Axes Colors. When the checkbox is clicked, page is submitted and checkbox status is stored and based on that Chart is rendered:
bool XAxisColor = (#ViewBag.XAxisColor) ?? true;
bool YAxisColor = #ViewBag.YAxisColor ?? false;
#Html.CheckBox("chkXAxisColor", XAxisColor, new { #Id = "chkXAxisColor",
onClick = "this.form.submit();" })
X Axis Color
#Html.CheckBox("chkYAxisColor", YAxisColor, new { #Id = "chkScatter",
onClick = "this.form.submit();" })
Y Axis Color
When first time the page is loaded, RenderCharts() Action gets called and Chart is rendered.
But when i Click any of the CheckBox, RenderCharts() Action gets called twice.
I could not understand this issue. I have created a sample Application which can be downloaded from here https://www.dropbox.com/s/ig8gi3xh4cx245j/MVC_Test.zip
Any help would be appreciated. Thanks in advance.
This appears to be something to do with Internet Explorer. Using your sample application, everything works fine in both Google Chrome and Firefox, but when using IE9, there are two Action requests on a postback.
Using the F12 developer tools on the network tab, it shows an initial request to RenderCharts which appeared to be aborted:
The (aborted) line in the middle is, I suspect, the additional request you're seeing. Why this happens, I don't know!
Finally got the answer. The problem was
runat="server"
in the Img tag.
Removing runat fixed the issue.
I can eliminate the IE issue in the following manner by simply using a bit of JQuery instead. A few possible advantages...
It eliminates the cross-browser issue.
It is an unobtrusive approach (not mixing javascript and HTML in the view).
You can update the image via ajax.
Create a new file in the scripts folder (e.g. "chart.js") which will simply attach an anonymous function to the the click events of your checkboxes from the document ready function. You would obviously need to include the script reference in your page as well:
$(document).ready(function () {
// Attach a function to the click event of both checkboxes
$("#chkXAxisColor,#chkScatter").click(function () {
// Make an ajax request and send the current checkbox values.
$.ajax({
url: "/Home/RenderCharts",
type: "GET",
cache: false,
data: {
XAxisColor: $("#chkXAxisColor").attr("checked"),
YAxisColor: $("#chkScatter").attr("checked")
},
success: function (result) {
alert(result);
$("#chart").attr("src", result);
}
});
});
});
Best of all, you get to eliminate the javascript from your view :)
...
<div style="margin: 2px 0 2px 0">
#Html.CheckBox("chkXAxisColor", XAxisColor, new { #Id = "chkXAxisColor" })
X Axis Color
#Html.CheckBox("chkYAxisColor", YAxisColor, new { #Id = "chkScatter" })
Y Axis Color
</div>
...
This is of course a very basic example which does eliminate the IE issue but you could get fancier from there in terms of how you update the image + show a loading gif, etc with only a few more lines.
Hopefully it is a workable solution for you!
I'm beginning in Ajax and I have a couples of problems. I have a page with a list containning some video thumbnails, when you rollover on them, there's a "I dislike this" icon showing. That's done. Now where iam having problem is:
When you click that icon, the video title, thumbnail & info should disapear and another video must show.
Here's my Ajax code
function ThumbsDown(id,sort,page) {
$.ajax({
url: "/change/videos/"+id+"/thumbsdown/",
type: "POST",
data: {
"sort": sort?sort:"",
"page": page?page:""
},
complete: function(result) {
// Instead of calling the div name, I need to be able to target it with $(this) and .parent() to make sure only 1 video change, but for now I only want the response to replace the video
$("#content .videoList ul li.videoBox").html(result);
}
});
}
The request is working, im gettin a (200 OK) response. And it's returning me the HTML code block for the new video.
The problem is, when I click the icon, all the html in the div is gone. I have an empty tag, so I guess its interpreted as "empty". But in my firebug .Net tab, I can see clearly that there IS a response.
Any help please? ALREADY FIXED, THANKS
** EDIT **
Now im having problems to target the specific div with$(this) and parents(). Can someone help?
I want to target the li #videoBox
<li class="videoBox recommended">
<div class="spacer" style="display: block;"></div>
<div class="features">
<div>
<a class="dislike_black" title="I dislike this" onclick="ThumbsDown(30835, 'relevance', '1');"></a>
</div>
...
I tried this, and its not working.
success: function(data) {
$("#content .videoList ul li.videoBox").html(data); // this IS WORKING, but replacing ALL the thumbs
$(this).parents("li.videoBox").html(data); // THIS IS NOT
What Im I doing wrong?
The problem you're having, is that you are using the "complete" callback function. This can be misleading, but that callback is meant to be called after a success or a failure. It's more for cleanup, and doesn't receive the response data as you would expect. Basically, all you need to do is change "complete" to "success", and you should receive your expected result.
However, I personally don't suggest using the Ajax function, since it looks like it's entirely unnecessary. The Ajax function exists mostly for complex transactions, and it looks like you have a fairly simple one. What I suggest, is using the "shortcut" function that jQuery provides, like so:
$.post(`/change/videos/${id}/thumbsdown/`, {sort:'', page:''}, function(result){
// Instead of calling the div name, I need to be able to target it
// with $(this) and .parent() to make sure only 1 video change,
// but for now I only want the response to replace the video
$('#content .videoList ul li.videoBox').html(result);
}, 'html');
Change from complete to success
function ThumbsDown(id,sort,page) {
$.ajax({
url: "/change/videos/"+id+"/thumbsdown/",
type: "POST",
data: {
"sort": sort?sort:"",
"page": page?page:""
},
success: function(result) {
// Instead of calling the div name, I need to be able to target it with $(this) and .parent() to make sure only 1 video change, but for now I only want the response to replace the video
$("#content .videoList ul li.videoBox").html(result);
}
});
}
the complete callback unlike the success doesn't get the data parameter, only the jqXHR parameter.