All for Joomla All for Webmasters

Tutorial: Writing A Modern Web Application With CodeIgniter, Ajax, and Rest

It is sure nice to have a framework handle all the logic in your web application, but without dynamic content loading, your web application will be seen as lacking and not modern. We don’t want to give the upper hand to the competitors by a mistake of implementation do we?

Today, i will write a long tutorial on how to serve content and have it updated via ajax. This article will be in three parts:

1 – Creating the table and writing the model

2 – Implementing CodeIgniter REST Server and use it to serve data

3 – Write the AJAX handlers in the UI Part

We will first start with creating the table and the model. We will name our objects “animals” as an example. In your own web application though, you will have at least 3-4 tables, different models, and you’ll operate on multiple models in your controllers.

Now let’s remember the MVC pattern: “Database logic in the models, Controlling logic (switching types, loading data to variables, echoing, calculations) in the controllers, and the presentation logic (HTML, JS) in the views). Point it out in the comments if i break this rule in my tutorials (though doubtful i ever will).

So, let’s create our table:

      CREATE TABLE animals (animal_id INT PRIMARY KEY AUTO_INCREMENT,
                            animal_name VARCHAR(128) NOT NULL,
                            animal_owner VARCHAR(128) NOT NULL,
                            animal_sex VARCHAR(1) NOT NULL,
                            animal_birth_date DATETIME);

Explanation: the animal id is the primary key for our tables (primary keys are used for database relations AND differentiating different rows with similar data), animal name is pretty obvious to me, animal_owner is the name of our owner, the sex, being a single character (either M for male or F for female).

The birth date, we will insert it by the database via the PHP date() function, but we will deal with that later.

Now, it is the time to write our model. In your CodeIgniter installation, create the following file under:

application/model/

A file with the name and extension:

animal_model.php

Now open that up and write the following code in there:

 class Animal_model extends CI_Model {

     public function __construct() {

	    parent::__construct();
		$this->load->database();

	 }

	 protected $tbl_name = "animals";

	 public function create_animal($animal_birth_date) {

	 	$this->db->set('animal_name',$this->input->post('animal_name'));
		$this->db->set('animal_owner',$this->input->post('animal_owner'));
		$this->db->set('animal_sex',$this->input->post('animal_sex'));
		$this->db->set('animal_birth_date',$animal_birth_date);

		$this->db->insert($this->tbl_name);

	 }

	 public function get_all_animals() {

	 	$query = $this->db->get($this->tbl_name);

		if($query->num_rows() > 0) {

		 return $query->result_array();

		}

	 }

	 public function get_animal_by_id($animal_id) {

	 	$query = $this->db->get_where($this->tbl_name , array('animal_id' => $animal_id));

		if($query->num_rows() > 0) {

		 return $query->result_array();

		}

	 }

	 public function update_animal_by_id() {

	 	$this->db->set('animal_name',$this->input->post('animal_name'));
		$this->db->set('animal_owner',$this->input->post('animal_owner'));
		$this->db->set('animal_sex',$this->input->post('animal_sex'));
		$this->db->set('animal_birth_date',$animal_birth_date);

	 	$this->db->where('animal_id',$this->input->post('animal_id'));

	 	$this->db->update($this->tbl_name);
	 }

	 public function delete_animal_by_id() {

	 	$this->db->delete($this->tbl_name,array('animal_id' => $this->input->post('animal_id')));

	 }

 }

Note: I omit the PHP tags because stupid WordPress doesn’t accept them, so you will have to do that yourself. Every Web Application’s Model object should have the following methods:

  • A method to create objects, via POST
  • A method to get objects, both the whole collection, and a single one (like i did by id)
  • A method to update objects, by the id (because Title is an unreliable option for finding the right object)
  • Finally, a method to delete objects by id.

You will see that i used a $tbl_name variable to have the table name there. That will be available to the model’s method via the $this reserved keyword  and it’s extending classes (albeit no class ever extends an user-written CodeIgniter model).

You will also see that i have called the parent constructor, because not doing so will make you lose the parent classes inside definitions (such as variables or methods) when extending it’s constructor.

I am also calling the $this-> load ->database ( ) method to load the database by the config. You can check the official documentation to see which parameters this function receives to do modifications on the database, you can also assign the value returned by it to have multiple connections to your database.

For creation and update logic, i use data directly data from POST because that’s what we will do from the controller for 100% conciseness.

You will also notice that i always return arrays (i hate dealing with objects except in result arrays). The main reason for this is because arrays are much much lighter than objects (see the Zend reference for comparing a size of an array to a size of an object in memory allocation) plus it is much prettier and easier to stick other arrays to an array. We don’t deal with instances etc. either.

Now before stepping to the second part of this tutorial, i want you to go and read up the Active Records reference (just throw an eye on it fast) to get an idea of what functions you have available to do operations on the database.

You have some options to extend this model, with functions like:

  • animal_ set_ sex ()
  • animal_set_birthdate()
  • animal_get_by_sex()

And you could write thousands of specific functions to get and set animals. Or you could be the smart guy and do:

        //Method to set value(s) for row(s) with a named column

        public function get_animals_by_column($column_name,$column_value) {

          $query = $this->db->get_where($this->tbl_name,array($column_name,$column_value);
          ......

And you just provide the column name and the value for that column, instead of having to write thousands of functions for the same kind of retrieval / insert.

We will use this model to dynamically get / set data on the view using AJAX and our Rest Controller. But in the following article our targets will be:

  • Setting up the PhilSurgeon CodeIgniter REST Server
  • Writing a Rest controller for our animals to do operations on the animals DB
  • Load the views for the web application

we will deal with the traffic cop part (The controller), and you will see how a web application makes decisions on which data to display to the user, and how to use the REST Server to write controller methods that write to the database, and retrieve new data, without you having to refresh.

So, we first have to install Philsturgeon’s CodeIgniter Rest Server.

Go download the whole zip from the github page and the steps to install are: Drag and drop the application/libraries/Format.php and application/libraries/REST_Controller.php files into your application’s directories. Either autoload the REST_Controller class or require_once it at the top of your controllers to load it into the scope. Additionally, copy the rest.php file from application/config in your application’s configuration directory. So let’s start with the controller:

require APPPATH.'/libraries/REST_Controller.php';

class Animals extends REST_Controller {

     public function __construct() {

	      parent::__construct();
		  $this->load->model('animals_model','animals');

	 }

	 public function index_get($id) {

                if(isset($id) {

                  $data['animal'] = $this->animals->get_animal_by_id($id);

                } else {

                 $data['animals'] = $this->animals->get_all_animals();

               }

		$this->load->view('animals_view',$data);

	 }

	 public function index_post() {

	     //No need to pass parameters, we already did on the model

		 $this->animals->create_animal();

	 }

         public function fetch_get($id) {

               if(isset($id)) {

                 echo json_encode($this->animals->get_animal_by_id($id));

              } else {
                  echo json_encode($this->animals->get_animal_by_id($id));

              }
         }

	 public function update_post() {

	       $this->animals->update_animal();

	 }

         public function update_get($id) {

            $data['object_id'] = $id;
            $this->load->view('animal_update_view',$data);
        }

        public function update_post() {

           $this->animals->update_animal();

        }

	 public function delete_post() {

	      $this->animals->delete_animal();

	 }

}

I will explain the usage of the methods that i have written in this controller, and they are:

  • index_get() shows the main view for the application. If id is provided in the URL like /animals/12, the view will show a single object in details, and if not provided, it will show all the information about the animals in the database to the user.
  • index_post() is a REST controller, that we will make an AJAX call to for creating a new animal, that will return success, which will cause the Java Script to refresh the page to see the newly inserted data.
  • The fetch_get() method is used for fetching data dynamically ( if need at all ) . We will not use this in this version of the tutorial though.
  • The update_post() method is used for updating information about the animals in our database.
  • The delete_post() method is used for deleting r0ws c0ntaining information about the animals in our database.
  • And of course, the update_get() function is for the update screen. We will use object_id from the view to make an AJAX call of POST.

The thing we are trying to achieve here is to be able to do all the CRUD operations (create, read, update, insert) via AJAX calls dynamically to not have our user’s page refreshed just for a create. We will rather do these operations on the same page and load new content for the user with a much smaller bandwith usage.

So here goes the JavaScript Code:

$(function() {

    $("#create_form").submit(function() {

        $.ajax({

            method : "POST",
            url : "/animals/create",
            data : $("#create_form").serialize(),
            async : true,
            dataType: 'json'

        }).done(function(data) {

            if(data.message === "success") {

                location.reload()

            } else {

                alert("Cannot create new animal. Please try again later");

            }

        });

    });

    $(".delete-button").click(function() {

        //Get the parent DIV
        var animal_id = ($this).parent().find("input[name='animal_id']").val();

        var parent = $(this).parent();

        //Make ajax request to the delete controller
        $.ajax({

            method : "POST",
            url : "/animals/create",
            data : $("#create_form").serialize(),
            async : true,
            dataType: 'json'

        }).done(function(data) {

            if(data.message === "success") {

                $(parent).fadeOut().remove();

            } else {

                alert("Cannot delete animal. Please try again later");

            }

        });

    });

});

Here, you will notice a deviation from the standard. We are not refreshing the page to see that the object is deleted. But rather, we will go with the following logic:

– Hide the animal_id in the parent div of the button (which is in the same div as the info about the animal)
– When the delete or update buttons are called, get the animal_id from the parent div (as we mentioned, it is in the hidden input in the same div)
– Make the AJAX request to the REST controllers that we wrote
– Either refresh the page (Which will result in partial content loading), or alert an error

I will now abstract what is happening overall.

Our purpose with all this design patterning and directly avoiding doing the usual thing, is that we want content to be DYNAMICALLY retrieved and inserted, via the following actions:

To retrieve an object, or a collection of objects:
– You make an AJAX call to a controller, which retrieves the data from the database, echoes it (resulting in the AJAX code retrieving the echoed text)
– The AJAX code retrieves the text, parses it, and decides if there was an error or not,
– It injects the new data in a div, deletes that div altogether, or updates information lively,

I am aware that in our controller, we are lacking alot of functionality, but this is just a small example for this tutorial, as we will extend this much more in the next version of this tutorial.

So, we will follow with the third part of this tutorial, which will include the HTML and the information on using the AJAX code. If you are impatient though, and have knowledge on how to write a view pretty fine, you can now include the following code in the head section of your HTML to include the Java Script file:

        <script src="  ">

Which will be enough to get your script running on the client side. Make sure to pay attention on the class and id definitions in the script. Implement the delete, update, buttons inside a div with the class name of your choice to make everything work.

Leave a Reply

Top