Jul 18, 2012

AJAX, JQuery, CodeIgniter and PHP

This is an extension of an earlier blog of mine, but this time I have built it using the CodeIgniter PHP framework. I have also spiced it up with a dynamic JQuery form (kudos to Charlie Griefer and this blog post for the code!)

If you want to get your hands dirty doing something a little harder then I suggest you check out my earlier blog on creating a login system with CodeIgniter.

If you are just getting started, have a look at my other blog posts, 'Ubuntu, LAMP and CodeIgniter' and the 'Extended JQuery Tutorial'.

Getting started

I am going to assume that you are working with a fresh installation of CodeIgniter that simply displays the welcome message. I am going to start from there so we don't get into any confusion!

First, unzip the CodeIgniter source into your web-server's root directory (if you followed my LAMP guide above, this will default to /var/www/). Rename the extracted folder to test (so in the default example, the CodeIgniter framework will be stored in /var/www/test/).

Now delete ALL the php files in /var/www/test/application/controllers and /var/www/test/application/views. We are going to start completely fresh!

The final step is to configure the framework to use our new controller (once we create it...), so edit the file /var/www/test/application/config/routes.php with the following line:
$route['default_controller'] = "home";
Now to make our main controller....

The Home page controller

  1. Create a file in /var/www/test/application/controllers named home.php
  2. Add in the following code:
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class Home extends CI_Controller {

        /**
         * Index Page for the home controller.
         *
         * Maps to the following URL
         *         http://example.com/
    index.php
         *    - or - 
         *         http://example.com/index.php/home
         *    - or -
         * Since this controller is set as the default controller in
         * config/routes.php, it's displayed at http://example.com/
         *
         * So any other public methods not prefixed with an underscore will
         * map to /index.php/home/<method_name>
         * @see http://codeigniter.com/user_guide/general/urls.html
         */
        public function index()
        {
            $this->load->view('view');
        }
    }

    /* End of file ajax.php */
    /* Location: ./application/controllers/home.php */
  3. That's it. All this does is load up our view, which is our next step.

The Home page view

  1. Create a file in /var/www/test/application/views named view.php
  2. Add in the following code:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>Test</title>

    <!-- JQuery code hosted by Google -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>

    <!-- Adding and Deleting form buttons -->
    <script type="text/javascript" src="form.js"></script>

    <!-- AJAX functionality -->
    <script type="text/javascript" src="ajax.js"></script>
    </head>

    <body>

    <form id="myForm">
    <div id="input1" style="margin-bottom:4px;" class="clonedInput">
    Name: <input type="text" class="name" name="name1" id="name1" />
    </div>

    <div>
    <input type="button" id="btnAdd" value="add another name" />
    <input type="button" id="btnDel" value="remove name" />
    <input type="button" name="submit" class="button" id="submit" value="Send" />
    </div>

    <div id="display">
    </div>
    </form>

    </body>
    </html>
  3. Our basic HTML page includes three JavaScript files (One is the JQuery API, the other two we write ourselves; see below). We have a form with an input text box and three buttons. The first two buttons add and remove input boxes from our form, while the last button performs our AJAX operation.

form.js - Dynamically adding form elements

  1. Create a file called form.js in /var/www/test/
  2. Add the following code:
    $(document).ready(function() {
                $('#btnAdd').click(function() {
                   

                    // how many "duplicatable" input fields we currently have

                    var num     = $('.clonedInput').length;                // the numeric ID of the new input field being added
                    var newNum  = new Number(num + 1);
     
                    // create the new element via clone(),
                    // and manipulate it's ID using newNum value
                    var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
     
                    // manipulate the name/id values of the input inside the new element
                    newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
     
                    // insert the new element after the last "duplicatable" input field
                    $('#input' + num).after(newElem);
     
                    // enable the "remove" button
                    $('#btnDel').attr('disabled','');
     
                    // business rule: you can only add 5 names
                    if (newNum == 5)
                        $('#btnAdd').attr('disabled','disabled');
                });
     
                $('#btnDel').click(function() {
                   
    // how many "duplicatable" input fields we currently have
                    var num = $('.clonedInput').length;

                   
    // remove the last element
                    $('#input' + num).remove();
     
                    // enable the "add" button
                    $('#btnAdd').attr('disabled','');
     
                    // if only one element remains, disable the "remove" button
                    if (num-1 == 1)
                        $('#btnDel').attr('disabled','disabled');
                });
     
                $('#btnDel').attr('disabled','disabled');
            });
  3. This function attaches a JavaScript function to the add and remove button. The code is pretty well commented by Charlie Griefer, so if you want to know more I suggest you go visit his blog post.

ajax.js - AJAX with JQuery

  1.  Create a file called ajax.js in /var/www/test/
  2. Add the following code:
    $(document).ready(function() {
        // This will run when the item of id 'submit' is clicked
        $("#submit").click(function() {

        // Grabs the text input
    from the form
        var name = [];
        $(".name").each(function() { name.push($(this).val()) });

        // Create the key-value pair for POST

        var dataString = 'string=' + name.join(' ') + '';

        // This creates the AJAX connection
        $.ajax({
           type: "POST",
           url: "index.php/ajax",
           data: dataString,
           dataType: 'json',
           success: function(obj) {
              $('#display').html(obj.message);
           }
        });
        return false;
        });
    });
  3. This will send all of our dynamically generated form elements to index.php/ajax (which we will now create). Hopefully the code and comments are self explanatory; if you have any problems just shout out in the comments!

The AJAX controller

  1. Create a file in /var/www/test/application/controllers named ajax.php
  2. Add the following code:
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class Ajax extends CI_Controller {


       /**

        * Index Page for this controller.
        *
        * Maps to the following URL
        * http://example.com/index.php/ajax
        * - or -
        * http://example.com/index.php/ajax/index
        *
        * So any other public methods not prefixed with an underscore will
        * map to /index.php/ajax/<method_name>
        * @see http://codeigniter.com/user_guide/general/urls.html
       */
       public function index()
       {
           $txtValue = "We have recieved: " . $this->input->post('string');

           echo json_encode(array('message' => $txtValue));

       }
    }

    /* End of file ajax.php */

    /* Location: ./application/controllers/ajax.php */
  3. You should now be able to run this on your web-server and have a dynamic form that sends and recieves AJAX!

References:

9 comments:

  1. Nice post, keep up with this interesting work. It really is good to know about this topic is being so thanks for sharing this!

    ReplyDelete
    Replies
    1. No problems mate! It's always hard trying to create useful tutorials that others will actually find useful!

      Good lick in you other endeavors!

      Delete
  2. I copy-pasted your codes in the appropriate files and directories. When I tried it, it just displayed the form (i.e. the view.php that is called by the controller home.php). When I enter a string in the textbox and then click any of the 3 buttons, nothing happens...

    ReplyDelete
    Replies
    1. Hi sheila,

      I will need more information for what is going on, but my initial guess is that I might have accidentally made a typo when I transcribed the code to my blog (and scrubbed the code of any identifying/personal information).

      If you could post the last few lines of your web-server error log (on Ubuntu Linus this will be /var/log/apache2/error.log, but you may have to do a Google search or read your configuration file to find where it is located on your system).

      For instance, a PHP error in one of my systems showed up in my log as:

      [Wed Oct 17 17:55:29 2012] [error] [client 192.0.0.1] PHP Fatal error: Call to undefined method Module_Form::tag_with() in /home/application/controllers/client/timesheet.php on line 10
      [Wed Oct 17 17:56:03 2012] [error] [client 192.0.0.1] PHP Parse error: syntax error, unexpected $end, expecting T_FUNCTION in /home/application/controllers/client/timesheet.php on line 38

      With this PHP error message I now know exactly which line is causing the problem, which object/variable, and the nature of the error.

      If you could post that information here I could offer better help!!

      Cheers,

      Nassar

      Delete
  3. Nice post, keep up with this interesting work. It really is good to know about this topic

    ReplyDelete

Thanks for contributing!! Try to keep on topic and please avoid flame wars!!