Ajax cannot cache - php

I want to cache the data in broswer so that broswer don't need to query the server in several minutes. I added php cache header but seems it doesn't work. Here is my ajax code and php code:
Ajax code:
function myAjax(name, callback) {
var url = './php/getJson.php?name=' + encodeURIComponent(name) + '&callback=?';
jQuery.getJSON(url, function(data) {
callback(data);
jQuery.ajaxSetup({ cache: true });
});
}
PHP code:
$seconds_to_cache = 3600;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
$lm = gmdate("D, d M Y H:i:s", time() - $seconds_to_cache/2) . " GMT";
header("Last-Modified: $lm");
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: public, max-age=$seconds_to_cache");
include_once('getData.php');
$output = $_GET['name'];
echo $_GET['callback'].'('.$output.')';
Thanks for MitchS and lenzai's help. This issue is solved. The cache:true option should be set before any ajax querying and old jquery libraries don't support caching. So make sure you are using the newest jquery library
For people who want a working example:
Ajax code:
var callback = function(data) {
alert("callback");
}
function myAjax(name) {
var url = './php/getJson.php?name=' + encodeURIComponent(name) + '&callback=?';
jQuery.ajaxSetup({ cache: true });
jQuery.getJSON(url, function(data) {
callback(data);
});
}
PHP code:
$seconds_to_cache = 3600;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
$lm = gmdate("D, d M Y H:i:s", time() - $seconds_to_cache/2) . " GMT";
header("Last-Modified: $lm");
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: public, max-age=$seconds_to_cache");
$output = '{"eventList":["event1","test event"]}';
echo $_GET['callback'].'('.$output.')';

You are setting the Last-Modified header to an hour ago and setting the max-age to be an hour.
This means at the point you send this data, it is already at the maximum age allowed for a cache and any subsequent requests must be resent.

I wrote a test project adapted from your on your code.
http://test-lenzai.rhcloud.com/index.html
Each time you press the button, it launches a new ajax request...
The query is sent twice then the browser cache is used!!!!
This is caused by JQuery :
the first query is appended &_=s135227990... ( some timestamp probably)
subsequent queries don't have this extra argument and all identical queries are effectively using cache.
Now the question is how to tweak jquery so that 1st and second ajax queries are identical

Related

How can i cache the result of rand()?

I want to cache the result of rand() for 5 minutes.
<?php
$sec = 300;
$expires = gmdate("D, d M Y H:i:s", time() + $sec) . " GMT";
header("Expires: $expires");
header("Pragma: cache");
header("Cache-Control: max-age=$sec");
echo "Test " . rand(1, 10);
Unfortunately, i don't know why my code doesn't work. Everytime i call the php file in my browser the random number is different.
Does anybody has an idea what the problem is?
Edit:
The headers are sent correctly, but everytime I reload the page, the Expires header changes.
When i print $_SERVER, The HTTP_CACHE_CONTROL header says no-cache.
Could that be the problem?
Ok, everyone here suggesting alternatives, including javascript, cookies, etc but that does NOT answer the question.
The question is to cache using headers for that explicitly a 304 NOT Modified response exists...
<?php
$sec = 300;
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']))
{
$if_modified=time($_SERVER['HTTP_IF_MODIFIED_SINCE']);
if($if_modified>time()-$sec)
{
Header("HTTP/1.1 304 Not Modified");
exit();
}
}
$expires = gmdate("D, d M Y H:i:s", time() + $sec) .' '. date_default_timezone_get();
$modified= gmdate("D, d M Y H:i:s", time()) . ' '.date_default_timezone_get();
header("Expires: $expires");
header("Last-Modified: $modified");
header("Pragma: cache");
header("Cache-Control: max-age=$sec");
echo "Test " . rand(1, 10);
There you go.
Caching random numbers with headers.
I want to cache the result of rand() for 5 minutes.It can be possible throw javascript code. But it store in cookie
// this fun call after every 5 miniute
setInterval(function(){
generate_and_cookie_random_fun();
}, 5000);
// this fun generate random number and sotre it to cookie
function generate_and_cookie_random_fun(){
var random_number = Math.floor(Math.random() * 6) + 1 ;
setCookie('name_of_cookie',random_number ,7); // here 7 mean seven days
}
// below code for cookie
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
document.cookie = name+'=; Max-Age=-99999999;';
}
The simple way is to store it into cookie and check that if cookie exists to show the stored number, otherwise generate new.
Something like this:
<?php
setcookie("random_number", rand(1, 10), time() + 300);
if(isset($_COOKIE['random_number'])) {
echo $_COOKIE['random_number'];
} else {
setcookie("random_number", rand(1, 10), time() + 300);
}

I have to click twice to get Ajax to work

I am working on a timetable for a school shedule.
On the site, there is a jquery ui datepicker, that can be clicked to update the timetable (based on the date that has been clicked on the datepicker)
Everything works except I have to click twice to update the timetable. So every other click gets the job done.
I narrowed my problem down to several points:
Caching - The browser uses the cached Data for the time table
Caching on the PHP side - I have maybe not set the correct headers to tell the browser not to cache data - Tried several headers - Maybe I am doing it wrong
I have to set the Ajax option caching to false - Tried it- Not Working
I have to maybe make the call syncronous so the browser waits for the response - Not sure about this - tried it though
I am making an ajax call inside the jquery ui datepicker onselect option. Like this:
Jquery Ajax Code
onSelect: function (date) {
//defined your own method here
// $("#timTableMon").empty();
// $("#timTableTue").empty();
// $("#timTableWen").empty();
// $("#timTableThur").empty();
// $("#timTableFr").empty();
$.ajax({
url : 'ajaxDate.php',
dataType: 'json',
cache: false,
type : 'post',
data : {
'sendDate' : date
},
success : function(data, status) {
$("#weekHeader").text(data.week);
$("#timTableMon").html(data.Mon);
$("#timTableTue").html(data.Tue);
$("#timTableWen").html(data.Wen);
$("#timTableThur").html(data.Thur);
$("#timTableFr").html(data.Fr);
// location.reload();
// window.location.href = "http://localhost /timeTable /public/test.php";
},
error : function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
PHP Code
$date = $_POST['sendDate'];
// $log->log_action("date from ajax", $date);
$date = new DateTime($date);
$week = $date->format("W");
// $log->log_action("week from ajax", $week);
// $log->log_action("week from ajax", $week);
$_SESSION['week'] = $week;
$timetable->week = $week;
header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Pragma: no-cache'); // HTTP 1.0.
header('Expires: 0'); // Proxies.
$messages = array();
$messages['week'] = $week;
$messages['Mon'] = $timetable->drawMon();
$messages['Tue'] = $timetable->drawTue();
$messages['Wen'] = $timetable->drawWen();
$messages['Thur'] = $timetable->drawThur();
$messages['Fr'] = $timetable->drawFr();
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
echo json_encode($messages);
Any help would be greatly appreciated. Thank you

php index.php, add to cart issue

I am having trouble executing this code in my index.php.
It says 'CartAction not set'
I need your help php gurus. I can display any files you need to fix this error.
Here is the code:
// Handle AJAX requests
if (isset ($_GET['AjaxRequest']))
{
// Headers are sent to prevent browsers from caching
header('Expires: Fri, 25 Dec 1980 00:00:00 GMT'); // Time in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
header('Content-Type: text/html');
if (isset ($_GET['CartAction']))
{
$cart_action = $_GET['CartAction'];
if ($cart_action == ADD_PRODUCT)
{
require_once 'C:/vhosts/phpcs5/presentation/' . 'cart_details.php';
$cart_details = new CartDetails();
$cart_details->init();
$application->display('cart_summary.tpl');
}
else
{
$application->display('cart_details.tpl');
}
}
else
trigger_error('CartAction not set', E_USER_ERROR);
}
else
{
// Display the page
$application->display('store_front.tpl');
}
It's because your code is expecting a parameter named 'CartAction' in the url
Example:
www.yoursite.com/?CartAction=ADD_PRODUCT
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. Source
You check if $_GET['CartAction'] has a value ( from the above url this superglobal variable has the value 'ADD_PRODUCT' )
What #Mackiee (in comments) and your error message are both telling you is that the problem is that there is a query parameter missing. The URL that calls this needs to include either ?CartAction=ADD_PRODUCT or &CartAction=ADD_PRODUCT

JSON working one place but not another

I'm redesigning my site to base it off WordPress, and in the process, I need to import some PHP/jQuery. I find that it works fine on the original page but not the new one.
Here are the results of the JSON dumps:
Old - empty as it should be because no data
New - doesn't like using $_POST['club'] to import
The code in both instances is:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "post",
url: "eventinfo.php",
data: $('#club').serialize(),
success: function(data) {
$('#right_inside').html('<h2>' + $('#club').val() + '<span style="font-size: 14px"> (' + data[0].day + ')</h2><p>Entry: ' + data[0].entry + '</p><p>Queue jump: ' + data[0].queuejump + '</p><p>Guestlist closes at ' + data[0].closing + '</p>');
},
dataType: "json"
});
});
$('#club').change(function(event) {
$.ajax({
type: "post",
url: "eventinfo.php",
data: $(this).serialize(),
success: function(data) {
$('#right_inside').hide().html('<h2>' + $('#club').val() + '<span style="font-size: 14px"> (' + data[0].day + ')</h2><p>Entry: ' + data[0].entry + '</p><p>Queue jump: ' + data[0].queuejump + '</p><p>Guestlist closes at ' + data[0].closing + '</p>').fadeIn('500');
},
dataType: "json"
});
});
</script>
And my eventinfo.php is:
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
include('guestvibe_functions.php');
connect();
$night = $_POST['club'];
$night = mysql_real_escape_string($night);
$query = "SELECT * FROM nights WHERE name = '" .$night. "'";
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$items[] = array("entry"=>$row['entry'], "day"=>getLongDateString($row['day']), "queuejump"=>$row['queue jump'], "closing"=>$row['closing']);
}
}
mysql_close();
// convert into JSON format and print
echo json_encode($items);
?>
It's late so I hope I've explained this alright. Any ideas what's wrong?
EDIT
I should add that both are on the same server / hosting plan. The new one is just one directory up.
see this answer for clues
I think you probably have either a newer version of PHP or different server settings on the new PHP server.
I see two possibilities.
The first is that on the new site the club= variable is not populated by AJAX when in the old site it is. Then you must discover why the serialize() does not include a variable called 'club'.
The second is that the club= variable wasn't necessarily populated even in the old site, and you just didn't get the notice warning.
In this case, modifying the code from
$night = $_POST['club'];
in
$night = isset($_POST['club']) ? $_POST['club'] : '';
should solve the problem.
UPDATE
I checked the site, but the eventinfo URL I received is different from the one you quote. What my Firefox got was:
http://www.guestvibe.com/wordpress/eventinfo.php
...which results in a 404 Error.

xmlhttprequest onlys gets to status 3

I have a simple search form with a search box and a result box.
When I type a search word a request is created like: http://www.site.com/php_handler.php?s=hello
In the php script and a result is given back to the script this way:
<?php return $s; ?>
The problem is that my htmlrequest stops at readyState 3 it doesn't get to 4.
The javascript looks like this:
var xmlhttp = sajax_init_object();
function sajax_init_object() {
var A;
try {
A=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
A=new ActiveXObject("Microsoft.XMLHTTP");
} catch (oc) {
A=null;
}
}
if(!A && typeof XMLHttpRequest != "undefined")
A = new XMLHttpRequest();
if (!A)
sajax_debug("Could not create connection object.");
return A;
}
function getSearchItem()
{
gs=document.forms.mainform.resultsfield;
var searchword=document.forms.mainform.searchform.value;
if (searchword.length>=3)
{
setWaitCursor();
clearResults();
var uri = "http://site.com/ajax_handler.php?s="+searchword;
console.log(uri);
xmlhttp.open("GET", uri, true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4) {
processResults(xmlhttp.responseText);
removeWaitCursor();
}else{
console.log(xmlhttp.readyState);
}
}
xmlhttp.send(null);
}
else
{
alert("please add at least 3 characters .");
}
}
Can someone tell me why it stops at 3?
edit: here is also the php code:
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
session_start();
//include main file
require_once($_SESSION["FILEROOT"] . "xsite/init.php");
//check if formulier is posted
$zoekterm = C_GPC::getGETVar("s");
$s="";
if ($zoekterm != "") {
$query="SELECT number,name,city,zib,zip_annex FROM articles WHERE version='edit' AND (naam LIKE '%$school%' OR brinnummer='$school') ORDER BY name";
if ($rs=C_DB::fetchRecordSet($query)) {
while ($row=C_DB::fetchRow($rs)) {
if ($row["plaats"]!="") {
$s.=$row["name"].", ".$row["city"]."|".$row["number"]."\n";
} else {
$s.=$row["name"].", ".$row["zip"].$row["zip_annex"]."|".$row["number"]."\n";
}
}
}
}
return $s;
?>
edit:
I missed a semicolon in my php script and now the ready state only gets to 2
edit:
The problem is even different. It gets to 4 but it doesn't show the result text.
1> Don't send Cache-Control: post-check=0, pre-check=0. These don't do what you think they do, and they're entirely unnecessary.
2> Your AJAX results page needs to send a Content-Length or Connection: Close header.
3> Try adding a random to your request URL to ensure you're not looking at a stale cache entry.
ReadyState 3 => Some data has been received
ReadyState 4 => All the data has been received
Maybe the XMLHTTPRequest object is still waiting for some data.
Are you sure your php script ends correctly ?
Is the content-length alright ?
To debug this you have two options, type the URL directly into the browser [since you are using a GET] and see what is happening.
OR
You can use a tool such as Fiddler and see what is exactly happening with the XMLHttpRequest

Categories