• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Caching AJAX Requests


At the moment, CodeIgniter only allows you to cache those requests which load or display views.

I'm looking for a way to let it cache ajax requests as well, e.g where you visit a URL like:


and it will cache the output of this particular URL and display that.

Any ideas on how to do this?

No, it caches requests that use the output buffer, which views do automatically. You can do what you're after by directly setting the output, like: $this->output->set_output($string); instead of calling a view,
or use CI's built in _output() method available to all controllers to set output.

So rather than:

echo json_encode( $myData);

I would do:

$this->output->set_output( json_encode( $myData) ) ;

Is that right?

2) Also, does it cache based on url arguments, e.g site.com/ajax/1/2 will be cached differently than site.com/ajax/2/2 and such?

3) Also, does it cache $_POST arguments, so if a $_POST argument is different then it could be set to not return the cached version and process it?

The cache filename is a md5() hash of the entire url. It does not cache anything having to do with POST, only the url and the output from that url.

So can you confirm that the set_output method is correct?

there's two kind of caching

first: caching the views content

second: database caching

I'm don't know about the set_output method
but you can easily make a simple call to view like that

$this->output->cache(5); // this will cache for 5 minutes

$data['myData'] = $myData;

and on the views folder create ajax folder and file1.php


echo json_encode( $myData);


if you need to cache your database

change the configuration of application/config/database.php

$db['default']['cache_on'] = TRUE;
$db['default']['cachedir'] = "somefolder";

Thanks, one more thing. Say I only want the cached stuff to be displayed after a user's logged in status has been verified.

E.g on site.com/ajax/1, only user id 1 should be able to view this page and not any other useri id.

Is it possible to have the cache code run only after the login code has run? I.e if I do:

if (! $this->auth->loggedIn() )
// Show error and return;


Will this always run the login code to decide whether to show an error or return the cached page?

as I know the page will be view from the cached data whether or not you put the code

$this->output->cache(10); // 10 minutes

and the cached file will remain for 10 minutes before deleting itself
or before you delete it yourself

so I suggest using caching just for the un-changeable pages for a long time
and if you use caching for blogs and forums it will be so ugly for the site

see here

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.