Hi I have got an ajax code as follows:
$.ajax({
type:"POST",
url: 'sample.php',
data:"data="+data,
success: function(server_response) {
$('.functions').ajaxComplete(function(event, request){
if(server_response == 0)
{
showmsg('An email with instructions to reset password has been sent to your email address. Please check it.');
}
else if(server_response == 1)
{
showmsg('Email address was not found in our database. Please enter a valid email address');
}
else
{
showmsg('Some problem occured while sending you an email. Please try again.');
}
exit();
});
The code works correctly first time. However if I submit the code without page refresh the previous response is received. Like if I load the page for the first time and I get reponse from sample.php as 0 the message is displayed correctly. However if I give an ajax call without page refresh and I get response from sample.php as 1, the previous message is displayed. Whatever output I get I will开发者_运维技巧 get the same message for all until I refresh the page. What's the problem? Code works correctly.
Your responses are being cached so you need to prevent that. There are three widely used solutions in case you use jQuery.
Setting up jQuery (instructs AJAX calls not to cache results)
$(document).ready(function(){
$.ajaxSetup({
cache: false
});
});
Random Math seed (added to the URL its makes the server believe its a new request)
$.ajax({
type:"POST",
url: 'sample.php?rnd=' + Math.random(),
data:"data="+data,
success: function(server_response) {
//... rest of the code
});
Using current timestamp as seed (same as previous except current timestamp is used)
$.ajax({
type:"POST",
url: 'sample.php?rnd=' + Date().getTime(),
data:"data="+data,
success: function(server_response) {
//... rest of the code
});
The first option is good in case a lot of ajax requests are made on a single page with no actual downsides.
The second option is almost always a good choice. It also has no particular downsides.
The third option is also good but it can be dangerous on pages which make more than one AJAX request per second because sometimes the same timestamp could be used for two different requests and the subsequent call will receive cached data.
EDIT: In case no $(document).ready()
is present on the page one can be added to the head section right before the ending </head>
tag.
<head>
<!-- Whatever code already exists in the head section -->
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({
cache: false
});
});
</script>
</head>
Have you confirmed that subsequent requests are actually received and processed on the server side code? What is the server side code returning on those cases? Maybe the problem exists there?
Based solely on this description, it sounds like the response is just being cached. $.ajax()
has an option to disable caching: cache: false
. That would force the jQuery code to submit the request to the server each time regardless of browser caching.
More information here.
精彩评论