CodeIgniter and Jquery Ajax

A few tips I’ve found when making these two play nicely:-

Bind Jquery events to the document with on()

The update button in my admin area list has a class=”jqupdate”.  There is a Jquery routine to create it and load it into a div that is waiting on the page. When these buttons are created by ajax calls they don’t exist in the DOM as seen by the initial page load, so I bind the click event to the document with Jquery’s on(), and use that to call a function which runs all the Jquery above.

// make sure .jqupdate click events are seen
$(document).on(‘click’, ‘.jqupdate’, function(){
makeUpdateForm(this);
});

// requires the this array from the on click event.
// the clicked element must contain data-uid=”xx”
function makeUpdateForm(self){
// load the update form
var updateId= $(self).data(‘uid’);
var loadUrl = “<?php echo base_url(); ?>admin/updateBP/”+updateId;
$(‘#cover’).fadeIn(300, function(){
$(“#formContainer”).fadeIn(1000, function(){
$.ajax({
url:loadUrl,
success: function(data){
$(‘#formContainer’).html(data);
}
}); // end ajax
});// end $(“#formContainer”).fadeIn(
}); // end $(‘#cover’).show(
}


 

Turn off  browser caching

Consider this in an admin area

  1. Menu  produces ajax requested list in <div id=”doAdmin”>
  2. Click on item to update
  3. update form appears, light box style – ajax
  4. on update box disappears and the list is updated – ajax
  5. re-edit that item and the original text appears in the form because it’s in the browser cache, and there’s been no new HTTP request to trigger a refresh

Each of those ajax requests needs to force the browser to avoid caching

Solution:

In your controller, or more tidily in a helper that you load write the following function

/**
 *noCacheHeaders()
 *use before views requested by ajax to force the browser to refresh the cahe
 */
 function noCacheHeaders(){
 $this->output->set_header("HTTP/1.0 200 OK");
 $this->output->set_header("HTTP/1.1 200 OK");
 $this->output->set_header('Last-Modified: '.gmdate('D, d M Y H:i:s', strtotime('now')).' GMT');
 $this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");
 $this->output->set_header("Cache-Control: post-check=0, pre-check=0");
 $this->output->set_header("Pragma: no-cache");
 }

and call it before loading any views that have been requested by an ajax request

$this->noCacheHeaders()