Using window.pushState with url change with ajax - javascript

I have a project that with every link clicked, the history.pushState gets activated and an address is being updated accordingly. I then have an ajax function that only loads the partial page. When the partial page is loaded, I then click on the item and the page gets redirected. However, when I click the back button, all I see is the partial ajax page and not the parent page.
Here's my code:
$('#brands a').click (function(e) {
e.preventDefault();
href = $(this).attr('href');
history.pushState({}, '', href);
$.ajax({
type: 'get',
url: '{{route("show.watches")}}',
success: function(data) {
$('#product-items').html(data);
}
})
})
The product-items loads items while the parent page retains the old information. I then click on the item and the page gets redirected. However, when I click the back button, all I see are the items without any styling and the parent page is gone. I was told to put
window.onpopstate = function(event) {
location.reload();
};
in my partial page, that's being loaded but it doesn't get activated until I press the back button the second time. What am I missing? Can anyone help?

Related

Best Way to Load Pages w/o Reloading

I am working on building a website that will not reload to a new page every time a link is pressed. I want to make something kind of like all enterprise/popular websites. (When looking in the network dev tab: notice that youtube page doesn't completely reload when you click on a link, same with google, same with Facebook for the most part. They all usually just reload the page content and nothing else.)
I would like only the HTML between the body tags to be changed (nothing else: no js,css, no head tags, etc).
It would seem like it is pretty easy. Currently, I am just using ajax to go out and fetch the html of the page, and load that into the body. Done! Not so fast... Three things (my code is at the bottom)
The js includes are located at the bottom of the page, right before the closing body and html tags. When looking in the network tab, it shows that the same js is always gotten again and parsed again. How do I prevent that?
Some pages will not load styles that are set. (note that all css, js, etc. scripts are the same for every page)
I want to make sure that the page is completely reloaded if the user leaves the website.
I am not sure if I am looking for a fix to the way I am doing it, but probably just a completely better different way to do it.
Here is my code:
$('a').on('click', function () { //on click of any <a> tag
var where = $(this).attr('href'); //gets url of the <a> attribute
$.ajax({
type: "GET",
url: where, //where is the variable defined above
success: function(a) {
// load next page
history.pushState({urlPath: where},"",where); //changes the link of the webpage
$('body').html(a); //changes the body of the webpage
document.title = $('#title').text(); //changes the title using some weird irrelevant method
}
});
return false;
});
$(window).on('popstate', function() {//on click of the back or forward button
$.ajax({
type: "GET",
url: window.location.href, //the url is the url that the back or forward button is set to
success: function(data) {
//console.log();
$('body').html(data);//replaces data
document.title = $('#title').text();//changes title using weird irrelevant method
}
});
});

window.history.pushState back button working, but not forward once clicked back

function processAjaxData(response, urlPath) {
window.history.pushState({}, '', '/user/index2');
$(window).bind('popstate', function () {
window.location.href = window.location.href;
});
Above is the function i'm using , once ajax response is true from controller . i get data as HTML and i dump it into body . then calls the above function, i change the URL
Everything works fine, once click back button i can go to Index1 (localhost/user/index1), page but then from Index1 page i click forward browser button , HTML wont update only URL changes to localhost/user/index2

Display Proper URL in Address Bar

I'm using Jquery/Ajax to load html pages into a div on my website. I get links certain class to open up in the specified div. When doing this the address bar remains www.example.com. Due to the fact that I do have several pages that I will like to be able to share; so when people visit the links it will take them to the website but with the specific page loaded into the div container.
Here's a few lines of my code
$( document ).ready(function() {
$.ajax({
method: 'GET',
url: "pages/promo.html",
success: function(content)
{
$('#contentarea').html (content);
}
});
});
$('.menu_nav') .click (function () {
var href = $(this) .attr('href');
$('#contentarea').hide() .load(href).slideDown( 'very slow' )
return false;
});
Unless the other pages are on your domain, you cannot do this. If the other pages are, see this StackOverflow question: Updating address bar with new URL without hash or reloading the page.
Here's the deal: since you are loading a new page and you want the URL of the browser to point to that page, you should just give users a link. They know how to use the back button. (You could use the information in the linked answer to to change the URL to something like this: http://www.trillumonopoly.com/other-website.com.)
You can use the history object.
$('#contentarea').html(content);
history.pushState({url: "pages/promo.html"}, "", "pages/promo.html");
With the use of the state {url: "pages/promo.html"} you can load your page into your div when your users navigate back/forward.
$(window).on("popstate", function(e) {
if (e.originalEvent.state != null)
{
// AJAX load e.originalEvent.state.url
}
})

History.js - Updating the initial state(first loaded page before push another state)

Sorry for my bad english :(
I tried History.js and it works for me, i can push new states and update the content when i use the back/forward browser button but i have a problem with the initial state.
First of all when the first page is called i replace the state, initialize it like this:
History.replaceState({state: initialDataToStore}, document.title, document.location.href);
When i click on a link, i push a state and i update the div#content using an ajax request like this:
$('body').on('click', '.js-nav',function(event) {
var url = $(this).prop('href');
History.pushState(state, 'title', url);
loadContent(state, url);
event.preventDefault();
});
When i use the back/forward button, the 'statechange' event is fired, so i call the loadContent function to update the div#content like this:
History.Adapter.bind(window,'statechange',function(){
var State = History.getState();
url = State.url;
loadContent(State.data, url);
});
That's the loadContent function :
function loadContent(state, url){
$.ajax({
url: url,
type: 'GET'
})
.done(function(data) {
$('#content').empty().append(data);
})
.fail(function() {
console.log("error");
});
}
I have a problem with the first loaded page if it has already a previous element in the browser history like this:
1- new tab or another page
2- first loaded page (that i force the replaceState)
3- ...
If i go back to "new tab or another page" using the browser back button then i click on the forward button > "first loaded page", i lose all the html "layout"(html, scripts, head, body ...), only the ajax response will be displayed(content to append to div#content).
P.S:
If i don't have a previous element "new tab or another page" on the history my "first loaded page" works correctly, i don't lose the Html layout .
What i have to do ?
Thanks

link onclick and input[type='button'] onclick behaves differently?

I have a piece of code where there's a link and a input button both calling a same onclick function. However, they behave differently.
<input type="button" onclick="undelete_this("profile.php", 42)" value="Undelete">
<strong>here</strong>
function undelete_this(url, id){
if(confirm("Are you sure you want to undelete this record?")){
if(id!=="" && id!=0){
var info = 'id=' + id +"&action=undelete";
$.ajax({
type: "GET",
url: url,
data: info,
success: function(){
window.location.href = ($(location).attr('pathname')+"?enter=false&id="+id);
},
error: function(jqXHR, exception, realexception) {
alert(jqXHR.responseText+" "+realexception);
}
}
)
}
}
return false;
}
when the button is clicked, the ajax status is success; but when the link is clicked, the ajax status is error (error code = 0) and the responseText is blank.
Is there anyone have an idea why this is happening?
Because having an empty href causes the page to be reloaded when the link is clicked. Reloading the page (generally: navigating to any URL) aborts any outstanding AJAX requests, which is why you get no response.
Possible solutions:
onclick="undelete_this("profile.php",42); return false;" will cancel the default action (reloading the page)
href="javascript:;" will make the default action a no-op, again preventing the page from being reloaded
You can't simply leave the href blank, because href='' is a link back to the current page (ie it causes a page refresh).
There is a way of making a link do absolutely nothing when clicked (unless Javascript events are bound to it).
<strong>here</strong>

Categories

Resources