Reputation: 233
I have a problem in the application I am building. And I have read many threads about the similar problem and have applied the suggestion given in those threads. However, the problem persists hence I write this.
The setup for is as follows:
index.php
, step_one.php
and calculation.php
.From the index.php
, I successfully load the step_one.php
via the Ajax call which is as follows:
$(document).ready(function () {
var nocache = Math.random() * new Date().getTime() + Math.random();
$("#bookings").click(function () {
$.ajax({
url: 'step_one.php?cach='+nocache,
type: 'post',
cache: false,
success: function (data) {
$("#contentLeft").html(data);
}
});
});
});
Note: step_one.php
is the html form.Then in step_one.php
, I enter the data in the form and send the form data to calculation.php
via another Ajax call that is as follows:
$("#viewprice").click(function () {
var nocache = Math.random() * new Date().getTime() + Math.random();
$.ajax({
url: 'calculate_quote.php?cache=' + nocache,
type: 'post',
dataType: 'json',
cache: false,
data: $("#stepOneForm").serialize(),
success: function (data) {
console.log(data);
$(".quote").append(data);
$(".quote").show();
document.getElementById("price").value = data;
}
});
});
The calculation.php
file, calculates the price based on the data it receives and return the json
to step_one.php
. This is how I return json
from calculation.php
:
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Expires: 0'); // Proxies.
echo json_encode($data);
Note: The first time I click the #viewprice
button, the price is correctly and successfully return to step_one.php
. However, when in step_one.php
I enter new data and re-click the #viewprice
button, nothing is returned from calculation.php
. And when I inspect the Network data, I see the calculation.php
gets duplicated there and only the first Ajax call will the data in its response.
And this running in the local machine in xamp. Would you please assist? What am I doing wrong here?
Upvotes: 4
Views: 157
Reputation: 233
I found the bug that was giving me headache. It was a logical error.
Background
I use tokens in my forms for security reason. So for each form, I generate a token on page load and store it in the session. Then when the form sends its data (including the token), I first check if the received token is in the session - if the token is found, I then use the receives values and use them to compute $data
which I then pass it to json_encode
function. After the token is found, I delete it.
So, the calculation.php
was not cached as my Ajax code is correct. Instead, the problem was when I resend the form data for re-calculation. During resend, the token in the session has already been deleted; therefore, the token I send with the form data could not be found in the session. Hence, data not computed and nothing is return.
Upvotes: 1