Solving page reload in HTML5 histroy - javascript

I have a problem with my code , iam using Html 5 history and its work fine in getting contents and changing url but when i refresh the page its show only the content without full page with css and here my code :
<script type="text/javascript">
$(function() {
$('.menuAnchor').click(function(e) {
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.get(url, {}, function (data) {
$(".contn_btm_mid_bg").html(data);
//$.validator.unobtrusive.parse(".contn_btm_mid_bg");
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}
</script>

I use history.js to change my URL using ajax and it works fine for me. Your CSS shouldn't really change if you have it linked in your document. Are you overwriting it?
Declare your CSS in the head of the page that you're doing the ajax call on and on ajax load only update the DIV or whatever element with the contents of the ajax call. I do that with this plugin and it works great for me. My CSS is always there even on page refresh.
<html>
<head>
<link rel="stylesheet" type="text/css" href=" linktoyourfile.css" media="screen">
<!--js files etc -->
</head>
<body>
<div class="contn_btm_mid_bg"><!--ajax contents--></div>
</body>
</html>
EDIT:
Since I can't see your HTML or structure I will just tell you how I might do it based on your comment.
Don't call the whole page. Just call the div that contains the content you want to import via ajax. Not the whole page. Link the CSS on all your included pages in the header. Then use a DIV to hold the content, when you call that page, just call the id of the DIV not the entire page. example
Your other pages:
Then in your ajax call if your divs have the same class in all the pages you can do this below. Make sure you link your CSS in your other pages too.
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.get(url, {}, function (data) {
$(".contn_btm_mid_bg").html($(data).find('.contn_btm_mid_bg').html());
//$.validator.unobtrusive.parse(".contn_btm_mid_bg");
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}

Related

Reload javascript on html change

In my site's index.html I have a div element that changes when a menu item gets clicked (with jquery). The pages that get inserted into this element all have some javascript functions in them. However, I load my javascript files in the index.html right before the body closes. These files don't 'reload' when this div element changes, so the javascript doesn't work on these pages. How would I fix this issue? Do I have to reload the javascript files on the change of the element? And if so, how?
edit:
Sorry, these are the codes for the page inserts:
$("li.load-page").click(function() {
var pagina = $(this).data("page") + ".html";
console.log(pagina);
$("#main-content").load(pagina);
});
main-content is an empty div in index.html.
In one of the pages that gets inserted I use the jquery accordion in my html for example, but it doesn't work since it's included in the head, and the page doesn't refresh on insertion:
$(function() {
$( "#accordion" ).accordion({
collapsible: true,
heightStyle: "content"
});
});
EDIT2: I have simulated my problem here: https://jsfiddle.net/ktoeon2f/2/
<script type="text/javascript" id="jsid">
//your script here
</script>
after onchange call
eval(document.getElementById("jsid").innerHTML);
after load
$("li.load-page").click(function() {
var pagina = $(this).data("page") + ".html";
console.log(pagina);
$("#main-content").load(pagina);
eval(document.getElementById("jsid").innerHTML);
// give an id (jsid) to script tag inside your loaded page
});
The problem was solved in this thread: jQuery: Changing the CSS on an element loaded with ajax?
The solution was to load the other function(s) in the succes function of an ajax call:
$('#main-content').load(
url,
function(){
accordionFunction();
}
);

Clean the CSS that was added while loading Ajax content

I am appending an HTML document into my current page using Ajax, and removing those added divs when the close button is pressed. The problem is that when I close, the divs are removed from the document but the CSS <link rel="stylesheet" href="style.css"> are not removed, and the number keep increasing as I load and unload Ajax content. How to completely remove the loaded document with the header content (css, js) of that page?
edit: i dont know why people dont want to answer but they just come to negative voting.
this is the code that i have used to add(append the html document)
$(function(){
$("a[rel='tab']").click(function(e){
pageurl = $(this).attr('href');
$.get(pageurl, function(html) {
$(html).hide().appendTo('body').fadeIn(500);
}, 'html');
//to change the browser URL to the given link location
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
//stop refreshing to the page given in
return false;
});
});
and this code to remove the divs
function close(){
$("#mainContent").fadeOut(500, function() { $(this).remove(); });
window.history.back();
} ;
I can't see the document that you are attempting to add/remove, but I'm guessing it looks something like this:
<link rel="stylesheet" href="style.css">
<div id="main-content">
<p>Blah blah blah</p>
</div>
So when you add that content, the whole thing is inserted. When you remove it, you are only removing the div#main-content. To remove everything, two ideas come to mind:
Preferably, wrap the document in another <div> and remove that instead
Alternatively, you could select <link> elements that are siblings of the 'div#main-content`, but that has the potential to be more unpredictable.
If the document you are adding doesn't look like that, then please explain in the OP what it does look like and where the <link> elements are coming from.
If you are doing something like a HTML preview in another page, look into creating an iframe instead. Use AJAX to create a temporary URL as the source. The advantage is that you avoid conflicts that occur when you effectively merge two DOMs.

How to .load() just a specific div from a page into a a target div, not the whole page

I have the following script that loads a page into a div and not just the targeted div. This is most evident when going back to my index and my header and footer are jammed into the <div id="contentspace"></div>.
I read on here somewhere that the div needs to be placed in it's own page prior to being displayed. Not sure which method would do that. Is this possible without hashtags Thanks for your help
<script type="text/javascript">
$(function() {
$('#header a').click(function() {
$('#contentspace').empty();
$("#contentspace").load(this.href, function(response){
console.log($('#content', response).html())
event.preventDefault();
});
});
});
</script>
The method .load() can load page fragment, simply by specifying a valid jquery selector next to the url.
$('myelement').load('page.html #content', function() {
...
});
Note that when loading page fragments, jquery will remove any SCRIPT element it might contain.
In you example, you would do:
$("#contentspace").load(this.href + ' #content', function(response){
...
});
Did you read the documentation at all? Take a look at the section titled Loading page fragments in the jQuery API for .load(). Essentially you just pass a selector along with the URL of the page to load as the first argument of the method.

Structure for handling several script loaded from ajax

So as many others I have a problem dealing with scripts from external pages I load with ajax.
Im trying to set up a page with an "admin panel" on top of it. I want to be able to navigate to several admin pages within the panel. The different admin pages have both internal <script>and external js-files that they include. The scripts are loaded as they should but they seem to stack up or are not being managed in a good way.
I made a small test on one of the admin pages:
$('.left-col').click(function () {
alert();
});
Here, whenever I return to this page it will bind another click to it so I then get two alerts each time I click the div. I can solve this easily by running $('.left-col').unbind(); in my ajax.success.
However for some admin pages there are tons of .click/.change/.live etc and I'm not even sure what they are (i.e. from external plugins). So can I somehow unbind/remove all of the scripts loaded from each of my ajax-loaded page without having to specify each elements? I know I can use selectors with unbind but it doesnt seem very effective to loop over each div/img/input etc and unbind, and I'm not even sure if it will work.
This is how I load the admin pages:
<script type="text/javascript">
$(document).ready(function() {
function reloadAdminPanel(url) {
if(typeof(url) === "undefined") {
var url = '/admin/panel/dashboard/';
}
$.ajax({
'success': function (data, textStatus) {
var jData = $(data);
// override links in admin to run reloadAdminPanel()
jData.find('a').each(function() {
var newUrl = $(this).attr('href');
$(this).click(function(e) {
reloadAdminPanel(newUrl);
return false;
});
});
$('div.panel__inner').remove();
$('body').prepend(jData);
delete jData;
},
'url': url
});
}
reloadAdminPanel();
});
</script>
Any help is appreciated, cheers!
The structure of the page:
<html>
<body>
<div class="panel__inner"> <!-- admin panel --> </div>
<!-- rest of project site -->
</body>
</html>
Maybe itd help if you show us the structure of the elements, but from the definition of "Remove" in Jquery, it should remove the element, its children, all events and any data associated to it.
Is div.panel__inner located inside your body tag? I see that you are doing a remove on the div, but prepending the data to $('body'). Can you remove the body contents itself?

Same JQuery click function for numerous links

I have a page that has multiple links with various attributes (these attributes will be pulled in from a database):
index.php
<html>
<head>
<script type='text/javascript' src='header.js'></script>
</head>
<body>
My_Link_1
My_Link_2
<div id='my_container'> </div>
</body>
</html>
My header.js file has:
$(document).ready(function(){
$('.link_click').click(function(){
$("#my_container").load("classes/class.project.php", {proj: $(this).attr('id')} );
return false;
});
});
class.project.php is pretty simple:
<?php
echo "<div id='project_container'>project = ".$_POST['proj']." : end project</div>";
?>
This loads and passes the ID variable (which actually comes from a database) to class.project.php. It works fine for the first link click (either link will work). Once one link is clicked no other links with this div class will work. It feels like javascript loads the class.porject.php and it will not refresh it into that #my_container div.
I tried running this as suggested by peterpeiguo on the JQuery Fourm, with the alert box for testing wrapped inside .each:
Copy code
$(document).ready(function() {
$('.link_click').each(function() {
$(this).click(function() {
alert($(this).html());
});
});
});
This seems to work fine for the alert box. But when applying it to .load() it does not reload the page with the new passed variable. As a matter of fact, it doesn't even reload the current page. The link performs no function at that point.
The example site can be viewed here: http://nobletech.net/gl/
I looked at the link you posted, and the problem is that when you're doing load you're replacing the elements on the page with new ones, thus the event handlers don't work anymore.
What you really want to do is target the load. Something like:
$("#project_container").load("classes/class.project.php #project_container", {proj: $(this).attr('projid')} );
This only loads stuff into the proper container, leaving the links and other stuff intact.
Ideally, the php script should only return the stuff you need, not the whole page's markup.
BTW- Caching shouldn't be an issue in this case, since .load uses POST if parameters are passed. You only have to worry about ajax caching with GETs
Sounds like the request is getting cached to me.
Try this:
$.ajaxSetup ({
// Disable caching of AJAX responses */
cache: false
});
Sorry but this might be completely wrong but after examining your XHR response I saw that you are sending back html that replaces your existing elements.
So a quick fix would be to also send the following in your XHR response (your php script should output this also):
<script>
$('.link_click').each(function() {
$(this).click(function() {
alert($(this).html());
});
</script>

Categories

Resources