I am creating a website where I want to load dynamically the pages through AJAX. I am using History.js but I think that I am not doing it very right.
Basically I have an index.php page and some other pages: portfolio.php, contact.php and so on. What those additional php files contain is a simple HTML/PHP code that has to dynamically replace the content of a DIV in the index page, called #post-content.
When I click on a menu link in the index page, with a onClick event the JS function showPage(), taking only the page name without ".php" as argument, is called. The function is declared as the following:
function showPage(page) { var History = window.History; History.pushState(null, page, "index.php?page=" +page); $("#post-content").load(page + ".php"); } In the above function there are also other visual effects implemented, like the fadeIn or fadeOut, but I removed them to make the code more readable here.
The function gives me everything I need, or almost. Testing my website with Google Chrome, if I click a specific link in the menu, for example "portfolio", I get to ?page=portfolio.php correctly. This does NOT happens if I type manually the URL in the browser (for example, if someone else gives me the direct link to that page). This is because the function showPage() is not called.
So I included an external code above the index.php page:
<?php if(isset($_GET['page'])) { // Checks if the url contains the "page" parameter. ?> <script> $(function() { showPage('<? echo htmlentities($_GET['page']); ?>'); }); </script> <? } ?> This gives me the result I want.
At this point I need an expert advice. Am I doing it right? Is this the right way to implement jQuery AJAX inside of a website? I think I'm doing it wrong, very wrong. Coes on the web are very different than mine, however everything looks like working well. What should I do?
Any help in this discussion will be greatly appreciated :) Thank you!