article

Saturday, June 15, 2013

jQuery and ajax with Codeigniter

jQuery and ajax with Codeigniter

application\controllers\products.php
<?php
class Products extends CI_Controller{
 
 function __construct(){
  parent::__construct();
 }
 
 function index() {
        $this->load->view('products');
    }
 public function get_all_users(){

  $query = $this->db->get('products');
  if($query->num_rows > 0){
   $header = false;
   $output_string = '';
   $output_string .=  "<table border='1'>";
   foreach ($query->result() as $row){
    $name = $row->name;
    $output_string .= '<tr>';
    $output_string .= "<th>$name</th>"; 
    $output_string .= '</tr>';    
   }     
   $output_string .= '</table>';
  }
  else{
   $output_string = 'There are no results';
  }
   
  echo json_encode($output_string);
 }
 }
?>
application\views\products.php
<script language='JavaScript' type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<button type='button' name='getdata' id='getdata'>Get Data.</button>
<div id='result_table'></div>
<script type='text/javascript' language='javascript'>
$('#getdata').click(function(){
    $.ajax({
            url: '<?php echo base_url().'products/get_all_users';?>',
            type:'POST',
            dataType: 'json',
            success: function(output_string){
                    $('#result_table').append(output_string);
                } // End of success function of ajax form
            }); // End of ajax call 
 
});
</script>

Related Post