I managed to setup a working example of using HTML5 History API. It works fine in Firefox, but in Chrome and IE11, every new press of the back or forward buttons makes page loading time much slower.
After 4 or 5 presses(going back and forth between two pages) it gets really slow.
Guess it is maybe down to on how I use AJAX to load the content, but why is it working nicely for the first few transitions between pages.
Here is a working link:
http://madebym.me/playground/AJAX-transitions/
And here is the code snippet that makes it all work:
loadContent = function () {
$.ajax({
url: pageUrl, success: function (data) {
$('#main-content').html(data);
}
});
if (pageUrl != window.location) {
window.history.pushState({ path: pageUrl }, '', pageUrl);
}
}
$(window).on('popstate', function () {
$.ajax({
url: location.pathname, success: function (data) {
$('#main-content').html(data);
}
});
});
$('a').on('click', function () {
pageUrl = $(this).attr('href');
loadContent();
return false;
});
Related
I have dynamically loaded content .task-listing. The click works because it does "show" the div. But the ajax request doesnt function properly. I get a 200 status in the console, but I get no response from the server. If I refresh the page, it works properly. Why would this occur? I cant figure it out, I have been researching for over 2 hours. When I use firefox it doesnt happen again until I close the browser...
$(document).ready(function () {
$(document).on("click", ".task-listing", function () {
var info = $(this).attr("id");
getTaskInfo(info);
$(".task-data").show();
});
});
function getTaskInfo(info) {
$.ajax({
type: "POST",
url: "/src/php/get-info-task.php",
dataType: "json",
data: "info=" + info,
success: function (response) {
alert("ok");
},
});
}
I have a heavily ajax based application wherein i only have a login page and the main page.
Most of my links are "ajaxed" and i have them done like this:
//get the href of the link that has been clicked, ajaxify ANY links
$(document).on('click', '.tree a', function () {
var link = $(this).attr('href'); //get the href off the list
$.ajax({ //ajax request to post the partial View
url: link,
type: 'POST',
cache: false,
success: function (result) {
$('#target').html(result);
$.validator.unobtrusive.parse($("form#ValidateForm"));
}
});
return false; //intercept the link
});
I want to implement "pushState" on my application and the first step that i have done so far is to add this code:
$(document).on('click', 'a', function () {
history.pushState({}, '', $(this).attr("href"));
});
Now it updates my address bar whenever i click on any of my links and the ajax content gets successfully loaded.
I am kinda new to this API so i don't know what am i missing but here are my issues so far:
when i press the "back" button, nothing happens. I read about "popstate" and browsed through SO to look for solutions but i can't
seem to make them work.
When i click the link from the history, i get the "raw" view of the child html w/o the layout from the master html. What do i need to do if i want it to be displayed like
it was clicked from my main application?
Most of my child views are either forms or list.
This code should help you :
function openURL(href){
var link = href; //$(this).attr('href');
$.ajax({
url: link,
type: 'POST',
cache: false,
success: function (result) {
$('#target').html(result);
$.validator.unobtrusive.parse($("form#ValidateForm"));
}
});
window.history.pushState({href: href}, '', href);
}
$(document).ready(function() {
$(document).on('click', 'a', function () {
openURL($(this).attr("href"));
return false; //intercept the link
});
window.addEventListener('popstate', function(e){
if(e.state)
openURL(e.state.href);
});
});
I have a problem with popstate, Basically my code works really well. I perform an AJAX request and pushState. The problem comes up when I hit the back button on the browser. The whole page will request AJAX again. As you know Github is using this method also but when we hit back button it will not request AJAX again. how does Github do that? This is my code :
function loadProducts(dataPage) {
$.ajax({
type: "GET",
url: test.php,
data: {page : dataPage},
dataType: "html",
cache: true,
success: function(checks) {
$(".ajaxpage").html(checks).fadeIn("slow");
}
});
};
window.onpopstate = function(event) {
if (event.state != null) {
var pop = event.state;
loadProducts(pop.dataPage)
document.title = pop.dataPage;
}
};
$('#product').on("click", ".paging a", function(e) {
e.preventDefault();
history.pushState({
dataPage: $(this).attr('href')
}, null, $(this).attr('href'));
loadProducts($(this).attr('href'));
});
i try to remove "loadProducts(pop.dataPage)" but the page did not show previous page that should be. only the URL had change.
What's wrong with my code?
I have a following javascript function mixed with MVC controller actions calls:
var loadPartialChapterAfterAnswer = function () {
$.ajax({
url: '#Url.Action("IsAuthenticated", "Story")',
type: "POST",
success: function(data) {
var isAuthenticated = data;
if (isAuthenticated) {
if ('#Model.IsPersonality' == 'True') {
loadPartialChapter();
} else {
$("#chapterContainer").load('#Url.Action("GetNextQuestion", "Story")' + '?storyId=' + '#Model.Id', function () {
selectedCounter = 0;
showOnlyOneQuestion();
});
}
} else {
window.location.href = '#Url.Action("RedirectToHomeRoute", "Home")';
}
},
error: function() {
alert("Error");
}
});
};
Every time I select one checkbox on my page(view) this function is called. Code works great in all browsers except in IE. In IE the ajax url #Url.Action("IsAuthenticated", "Story") is called OK every time, but the other controller action '#Url.Action("GetNextQuestion", "Story")' + '?storyId=' + '#Model.Id' is called only when the IE's browser debugger is turned on. When IE's debugger window is off this second MVC action is never called.
Any help is highly appreciated!
SOLUTION
I added at the beginning of my page this code:
<script>
$.ajaxSetup({
cache: false
});
</script>
and now it works! Thanks all for your effort.
I read something about IE having issues with JQuery load function
Try to replace it with regular $.ajax with cache: false option hopefully it will resolve the issue.
Check this topic
Add controller to this: #Url.Action("GetNextQuestion")'
Without controller specified it place controller which return view last.
How can I load the first page of an MVC 4 application via AJAX?
I already have the structure set-up to load all the subsequent pages, but I've just hit a brick wall.
After adding the history management through history.js, I've changed my partial views to have a back button - which works as expected.
My problem is that after navigating to a couple of pages and then pressing the Back button, when I get to the first item on the windows history - i.e.: the index.chtml page - this page loads with the navigation bar appearing twice. After pressing F5, the page loads correctly.
What I'm doing wrong and what is the best way to fix this?
Thanks in advance for your help
By the way, this is the JavaScript I'm loading on the Layout View:
$(function () {
var contentShell = $('#bodyContent');
var History = window.History, State = History.getState();
$(".ajaxLink").on('click', function (e) {
e.preventDefault();
var url = $(this).data('href');
var title = $(this).data('title');
History.pushState(null, title, url);
});
History.Adapter.bind(window, 'statechange', function () {
State = History.getState();
navigateToURL(State.url);
});
function navigateToURL(url) {
$.ajax({
type: "GET",
url: url,
dataType: "html",
success: function (data, status, xhr) {
contentShell.html(data);
},
error: function (xhr, status, error) {
alert("Error loading Page.");
}
});
}
$('.history-back').on('click', function (e) {
e.preventDefault();
History.back();
return false;
})
});
This looks for me like a known problem, bug related to the click events which are fired twice in some browsers. This behavior is causing the History.pushState(...) in your code to execute twice.
You can try to add sth. like e.stopPropagation() to your code after. More on that problem you can find here: https://stackoverflow.com/a/21511818/2270888
Try something like this in your "first item" controller action:
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
return PartialView();
}
return View();
}