I started to work with ajax some time ago, but I'm getting a strange problem that I don't have any idea of the reason.
I work with 3 files to make all my pages: a header, a footer and the content files. In header I put my ajax code that is something like this:
$(document).on("click", '.ajax a', function (e) {
e.preventDefault();
var href = $(this).attr("href");
if (href == location.pathname) return; // Prevent from refresh on click the current page link
loadContent(href); // Make the AJAX call
window.history.pushState('', '', href); // Changes the link
});
//MAKE BACK/FORWARD WORKS
window.onpopstate = function(event) {
loadContent(location.pathname);
};
///////////////////////////////////////AJAX ITSELF
function loadContent(url){
$.ajax({
url:url,
type:'GET',
error: function(){
alert("Oops, something went wrong :(");
},
success:
function(data){
$('#content').html(data); // Inject page into the content div
document.title = $("#titulosads").val(); // Changes the page title
}
});
}
After that I open the #content
div
that will be closed in footer.
And in each page file, I use these codes for include the header.php
and the footer.php
when is needed:
function includeheader($pagename, $pagedescription)
{
$title = $pagename;
$description = $pagedescription;
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo "<input type='hidden' id='titulosads' value='".$title."' />";
} else {
include 'header.php';
}
}
And for the footer:
function includefooter()
{
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
} else {
include 'footer.php';
}
}
So, basically, this is my pages:
<?php
include_once 'includes/checkajax.php';
includeheader('Contact');
?>
Content of the page here!
<?php
includefooter();
?>
Well, this is my issue: it gets a little strange when I use the GET method of AJAX.
Things get duplicated when you click in other link and back on the first. You can check it on http://feely.com.br
When I change the method to POST or when I activate chrome dev tools that disable the cache, everything works fine.
Oh, there is a lot of errors on console that I don't have idea about what they mean.
A picture of the errors:
Help :(