Skip to content

Instantly share code, notes, and snippets.

@nicksheffield
Created May 18, 2011 07:08
Show Gist options
  • Save nicksheffield/978117 to your computer and use it in GitHub Desktop.
Save nicksheffield/978117 to your computer and use it in GitHub Desktop.
Ajax Pages
<?php
class Base_controller extends CI_Controller {
function __construct(){
parent::__construct();
}
function _page($view,$data = false){
if(IS_AJAX){
$this->load->view($view,$data);
}else{
$this->load->view('header',$data);
$this->load->view('nav',$data);
$this->load->view($view,$data);
$this->load->view('footer',$data);
}
}
}
<?php
// add this line to your application/config/constants.php file
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']));
<?php
include(APPPATH.'controllers/base_controller.php');
class Home extends Base_Controller{
function __construct(){
parent::__construct();
}
function index(){
$data['title'] = 'Hello World!';
$this->_page('home_view',$data);
}
}
$(document).ready(function() {
// if the browser supports the html5 history api
if(Modernizr.history){
// when a nav link is clicked
$('nav a').click(function(){
// if this link is already .current, then don't load it again
if($(this).hasClass('current')){
return false;
}
// store the link itself for later use.
var link = $(this);
// store this links url for later use.
var url = $(this).attr('href');
// change the cursor to look like a normal page load
$('body').css('cursor','progress');
// load the page that this link points to
$.ajax({
type:'post',
url:url,
success:function(newpage){
$('#page').fadeOut(200,function(){
// replace the current page content with the new content
$(this).html(newpage).fadeIn(200);
// remove the .current style from every nav button
$('nav a').each(function(){
$(this).removeClass('current');
});
// set the cursor back to normal
$('body').css('cursor','auto');
// add it back onto this one
link.addClass('current');
});
}
});
// change the address bar with the new html5 history api
window.history.pushState(null,null,url);
// change my page title to reflect the location of the new page
$('title').text(url + ' - Your Website');
// for debugging purposes, output to the console
if(window.console) console.log('Ajax page: ' + url.capitalize());
// disable the default clicking action
return false;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment