Posting form data using CodeIgniter and Ajax

Written by billy

Topics: Codeigniter

Using Ajax to post form data has been made really simple with jQuery’s Ajax methods. Here I’ll show you how to post data to a controller using the jQuery javascript library and the Codeigniter PHP framework

In this example I am just going to show you how to post data to a controller. The data is a comment for an article. I am going to create a controller called comment.php and a view called create_comment.php.

All this code is going to do is let the user enter a comment and post the comment to the controller which will process the comment and return true or false as the status.

Here is the comment.php controller:

<?php

class Comment extends CI_Controller{

function  __construct() {

    parent::__construct();
    $this->load->helper('url');
}

function create(){

    if($_POST):

        // do database stuff here to save the comment.

        // return false if db failed

        // else

        return true;

    endif;

}

}
?>

That’s all we need of the controller to know that our ajax post worked correctly.

Here you could build in the form helper to validate user data etc.

Here is part of the view file create_comment.php. This will give us the form to submit our comment. 

Note. You will need to have a recent version of the jQuery library loaded first…

<h3>New Comment</h3>
<form id="comment" method="post">
<label>Name: </label><input type="text" name="name" /><br />
<label>Comment: </label><textarea name="comment_text" cols="25" rows="10"></textarea><br />
<label>&nbsp;</label><input type="submit" value="Submit" />
</form>

<!-- here is the script that will do the ajax. It is triggered when the form is submitted -->
<script>
   $(function(){
       $("#comment").submit(function(){
         dataString = $("#comment").serialize();

         $.ajax({
           type: "POST",
           url: "<?php echo base_url(); ?>index.php/comment/create",
           data: dataString,

           success: function(data){
               alert('Successful!);
           }

         });

         return false;	//stop the actual form post !important!

      });
   });
</script>

This script will post the data to the controller. Since the controller is returning true the success function should start in which you will get an alert box saying Successful!

5 Comments Comments For This Post I'd Love to Hear Yours!

  1. Shouldn’t that be dataType: json, not jason? ;-)

  2. Rob Allport says:

    CI has an input helper for this – see http://codeigniter.com/user_guide/libraries/input.html towards the bottom of the page.

    Also, not surwe why you’re directly accessing the POST aray in CI either, styuff like “if($_POST):” shouldn’t be there.

Leave a Comment Here's Your Chance to Be Heard!