Thursday, May 31, 2012

Using jQuery and ajax with Codeigniter

To integrate jQuery with codeigniter, might sound a bit scary at first, but mind you, it’s not something out of this world. We will implement the same example from the previous jQuery post. We will use the same html page used in previous post of ajax jquery, and will only change how our PHP script will look, making it specific for codeigniter. Thus, making this post a bit vague for those that do not know how this works yet. Again, I recommend all that have not read my previous post, to do so.
The final resulting html page was:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><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: "getdata.php",            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>

Only one change needs to be done to this page, and it lies within the ajax call. Since we are using codeigniter, then we all know that the standard way of calling a function and a method is through the url and looks something like, the base_url / controller / function / additional parameters. In this particular example, we will create a new controller named profiles. Within the controller, we are going to have a function named: get_all_users(), so in this html page, we are going to change the ajax url parameter to this:

url: "<?php echo base_url().'profiles/get_all_users';?>"


Or if you have removed the index.php then:

http://www.yourdomain.com/products/get_all_users


Now, instead of having that ‘getdata.php’ file, we will create the products controller file for this task we are going to run. It will basically do the same process, except in a ‘codeigniter’ kind of way. Let’s create it:
Note: for the sake of this tutorial, I will place my logic within the controller, but the best practices are to create your logic within a model.
File name: products.php


<?phpclass 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);    } }?>



This logic is a bit simpler than the original post, but it’s just to get the idea on how to create an ajax, jquery connection using codeigniter. The html page should look something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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>

No comments:

Post a Comment