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)
Random Math seed (added to the URL its makes the server believe its a new request)
Using current timestamp as seed (same as previous except current timestamp is used)
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.