article

Friday, June 7, 2013

Using jQuery and ajax with Codeigniter

Using jQuery and ajax with Codeigniter

change the ajax url parameter to this:
    url: <?php echo base_url().'profiles/get_all_users';?>
http://www.yourdomain.com/products/get_all_users



<?php
//products controller
class Products extends CI_Controller{
    
    function __construct(){
        parent::__construct();
    }
    
    public function get_all_users(){
 
        $query = $this->db->get('products');
        if($query->num_rows > 0){
            $header = false;
            $output_string = '';
            $output_string .=  "<table border='1'>\n";
            foreach ($query->result() as $row){
                $output_string .= '<tr>\n';
                $output_string .= "<th>{$row['value']}</th>\n";    
                $output_string .= '</tr>\n';                
            }                    
            $output_string .= '</table>\n';
        }
        else{
            $output_string = 'There are no results';
        }
         
        echo json_encode($output_string);
    }
 }
?> 
<html>
<script language='JavaScript' type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<title>Display Page</title>
</head>
<body>
<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().'profiles/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>
</body>
</html>

Related Post