Skip to content

Instantly share code, notes, and snippets.

@MauMaGau
Created April 4, 2012 13:48
Show Gist options
  • Save MauMaGau/2301194 to your computer and use it in GitHub Desktop.
Save MauMaGau/2301194 to your computer and use it in GitHub Desktop.
PHP/JS: Codeigniter Ajax
<?php
/* CI AJAX */
public function index( $output_type ){
// the main controller logic...
switch( $output_type ){
case( 'JSON' ): $this->load->view( 'JSON/simple' , array('JSON'=>$view_data) );
break;
default: $this->load->view( 'regular_page', $view_data );
}
}
?>
<script>
/* AJAX */
var base_url = $('base').attr('href'); // Assumes html contains a base element indicating the base url
$( 'form.ajax' ).live( 'submit', function(){ // Using the live function allows the form to be retrieved even if it's created after the original DOM load.
var action_url = base_url + $( this ).attr( 'action' ); // Assumes the same controller that handles the form w/o ajax will handle it with ajax.
/*console.log(action_url);*/
$.ajax({
url: action_url+'/json', /* Assumes the controller accepts the final parameter as an output type switch */
type: 'POST',
data: "key1="+$( this ).children( 'input[name=key1]' ).val()+"&key2="+$( this ).children( 'input[name=key2]' ).val(),
async: false,
success: function( response ) {
ajaxOutput = $.parseJSON( response );
}
});
/* console.log(ajaxOutput); */
if( ajaxOutput.success=='TRUE' ){ /* Assumes JSON contains a success property */
console.log(ajaxOutput);
}else{
console.log(ajaxOutput);
}
return false; // Prevents form submitting
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment