Você está na página 1de 5

Code Igniter jQuery and Ajax

Amitav Roy on 22nd Jan 2012

In this tutorial I will show you how to use the jQuery and Ajax inside the Code Igniter framework. We will create a page where we will create a drop down of states coming from the database. And once a state is selected, the list of cities will come through Ajax.
To setup first we will create a Site controller which will display a drop down of States. Our job will be to display the list of cities based on the states. Although this should be done using a simple javascript array inside the page in normal condition because this is not a very important data to have a server call. But for sake of tutorial, this is nice :) Here is the snapshot of the database table for the state and city:

Database screenshot

[NOTE: Remember, if this you need to connect to database in code igniter, you need to do some configuration which is not included in this tutorial. Refer this link to check that:http://www.amitavroy.com/justread/content/articles/codeigniter-php-framework-quick-and-easy%E2%80%93-part-1 and check the Basic Configuration to the Framework section.] Here is my Site controller: class Site extends CI_Controller { /** * The __construct function is called so that I don't have to load the model each and every time. * And any change while refactoring or something else would mean change in only one place. */

function __construct() { parent::__construct(); $this->load->model('state_city_model'); } /** * This is the first method which get's executed when someone will go to the site section. */ function index() { //Calling the get_unique_states() function to get the arr of state. Model already loaded. $arrStates = $this->state_city_model->get_unique_states(); //Getting the final array in the form which I will be using for the form helper to create a dropdown. foreach ($arrStates as $states) { $arrFinal[$states->state] = $states->state; } $data['states'] = $arrFinal; //Passing $data to the view, so that we can get the states as an array inside the view. $this->load->view('site_index',$data); } function ajax_call() { //Checking so that people cannot go to the page directly. if (isset($_POST) && isset($_POST['state'])) { $state = $_POST['state']; $arrCities = $this->state_city_model>get_cities_from_state($state); foreach ($arrCities as $cities) { $arrFinal[$cities->city] = $cities->city; } //Using the form_dropdown helper function to get the new dropdown. print form_dropdown('cities',$arrFinal); } else { redirect('site'); //Else redire to the site home page. } } }

Here the first is the construct function will be executed every time the site class is initiated. [NOTE: Constructor functions are handy way of loading models and helpers instead of every time making a call to load them.] Inside index, we are first building the $arrStates in which we have saved the result from the state_city_model function inside the state_city_model and then I have changed the way I want the final array which I am padding to the view because I will be using the array to create my dropdown using the form helper of Code Igniter. Next in the controller is the ajax_call which is where the server request is made through ajax when the drop down is changed. This is almost the same concept to the index method except that here I have to print the output instead of passing it to any view. Here we are using the get_cities_from_state function inside the state_city_model model passing the state as the argument so that we will get only those cities which are inside the desired state coming through the ajax call. Here is the code for the mode State_city_model: ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

class State_city_model extends CI_Model { /** * This funtion will return me the result of all the states. * This has to be unique because the states will be repeating. */ function get_unique_states() { $query = $this->db->query("SELECT DISTINCT state FROM state_city"); if ($query->num_rows > 0) { return $query->result(); } } /** * This function will take the state as argument * and then return the cities which fall under that particular state. */ function get_cities_from_state($state) { $query = $this->db->query("SELECT city FROM state_city WHERE state = '{$state}'"); if ($query->num_rows > 0) { return $query->result(); } } }

Here both the functions are almost identical except that in the second one the query has an extra where clause where I am taking the state as an argument. Remember, I have not used the Active records of Code Igniter to do this fast, but you should always use that instead of the normal queries. And last but not the least is the View:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

<?php //Initial $this->load->helper('html'); ?> <html> <head> <title>jQuery Ajax tutorial using Code Igniter Framework</title> <script type="text/javascript" src="http://code.jquery.com/jquerylatest.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#states-dropdown select').change(function () { var selState = $(this).attr('value'); console.log(selState); $.ajax({ url: "site/ajax_call", //The url where the server req would made. async: false, type: "POST", //The type which you want to use: GET/POST data: "state="+selState, //The variables which are going. dataType: "html", //Return data type (what we expect).

//This is the function which will be called if ajax call is successful.

success: function(data) { //data is the html of the page where the request is mad $('#city').html(data); } }) }); }); </script> </head> <body> <div id="wrapper"> <div id="states-dropdown"><?php print form_dropdown('states',$states); ?></div> <div id="city"></div> </div> </body> </html>

Here from line 14 is the main thing which is going on. $.ajax is the function which says that url: site/ajax_call is the page where the request should be made. Type will be POST and the data: is the actual data which will pass as POST variable to the page. And then on success, a function is called which simply changes the HTML of the #city div with the new one. That was simple. Isn't it? Oh, and here are the screen shot of the thing working. No CSS or beautification, but it work never the less.

Você também pode gostar