I want to reload on the content area of my website with jQuery/AJAX $().load()
function. But my problem is that the header
and footer
needs to be displayed on all pages no matter your entry URL.
My site is build using templates, so my first thought was to remove the output of the layout above and below the unique content, as I would then prevent ie. the menu from being displayed twice. But I realized that if the user is not entering my site through the first page, lets say index.php, he won't ever see header or footer just an unstyled text page.
My question is, how would you work around this issue? JavaScript (+ jQuery) and HTML5 is allowed.
page.php:
<div id="header"></di>
<div id="mainContent"></div>
<div id="footer"></div>
js:
$("#content").load("page.php #mainContent"); //that will only load mainContent
or:
$.get('page.php', function (data) {
data = $(data).find('#mainContent').html();
$("#content").empty().append(data);
});
For more information, see the section in the jQuery documentation on load() and page fragments
It seems like you could have a couple of different options. If a user is visiting your site but not going to the first page, then you could just check to verify that the header and footers are showing after the page is loaded. If they are not found, then the initial site layout should be created. You could even decide to build the first page (index.php) this way so that every page would be handled the same way
$(document).ready(function() {
// If an element of id "header" isn't found in the DOM
if (!$("#header").length() > 0) {
// Generate the header and insert it as the first element of the DOM
}
if (!$("#footer").length() > 0) {
// Generate the footer and append it to the last element of the DOM
}
});
There are no doubt other solutions that you could entertain as well; you could probably have an include on each page that only gets included if the page is requested via a GET rather than an AJAX request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With