Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$().load() instead of loading whole page, but need to keep menu on all pages

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.

like image 619
Emil Avatar asked Apr 15 '12 22:04

Emil


2 Answers

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

like image 120
mgraph Avatar answered Oct 04 '22 20:10

mgraph


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.

like image 21
veeTrain Avatar answered Oct 04 '22 20:10

veeTrain