Web DesignWeb Dev

Tutorial: Writing A Modern Web Application with CodeIgniter, Ajax, and Rest (Part 2)

0

ci_logo_flame[1]In the last tutorial that i wrote with the title that you see up, i have described how to write a model for the retrieval / insertion / updating / deleting operations that you will want to do on your database in your shiny new web application. In this part though, 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.

See you in the continuation of this tutorial, the view part!

Tutorial: Writing A Modern Web Application With CodeIgniter, Ajax, and Rest (Part 1)

Previous article

Top 10 Recovery Software For Your Home and Business Computers

Next article

You may also like

Comments

Comments are closed.

More in Web Design