I made an ajax script that call the page asked in a #container
div in php, so if i call the project.html page, the request working well, calling the page and the $getscript
associate but if i try to call back my home page the requests are duplicate:
There is my php function:
<?php $d="pages/" ; if(isset($_GET[ 'p'])){ $p=strtolower($_GET[ 'p']); if(preg_match( "/^[a-z0-9\-]+$/",$p) && file_exists($d.$p. ".html")){ include $d.$p. ".html"; } else{ include $d. "404.html"; } } else{ include $d. "home.html"; } ?>
and this is my ajax request:
var afficher = function(data, page) {
$('#container').fadeOut(500, function() {
$('#container').empty();
$('#container').append(data);
$('#container').fadeIn(100, function() {});
});
};
var loadPage = function(page, storeHistory) {
if (typeof storeHistory === 'undefined') {
storeHistory = true;
}
$.ajax({
url: 'pages/' + page,
cache: false,
success: function(html) {
afficher(html, page);
if (storeHistory === true) {
history.pushState({
'key': 'value',
'url': page
}, '', page);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
afficher('erreur lors du chagement de la page');
}
});
return false;
};
window.addEventListener('load', function() {
setTimeout(function() {
window.addEventListener('popstate', function(e) {
if (e.state === null) {
loadPage('home.html');
} else {
loadPage(e['state']['url'], false);
}
});
}, 0);
});
$(document).ready(function() {
$('.project a').on('click', function(e) {
var page = $(this).attr('href');
loadPage(page);
return false;
});
$('#menu a').on('click', function() {
var page = $(this).attr('href');
loadPage(page);
return false;
});
});
How can i fix the problem of multiple request when i call my home page ?
The problem here is somehow the event is getting added again and again. One temperary solution and suggested solution will be to abort the previous ajax everytime you call another ajax. So it can be:
var lastRequest = null;
if(lastRequest!=null){
lastRequest.abort();
}
lastRequest = $.ajax({
//your code
});
So, by this way there will only one active ajax at a time.
Hope that helps.