How to Submit Form using AJAX in CodeIgniter

Hi! This post will show you how to submit form using ajax in codeigniter. Generally when you submit html forms - page will be refreshed. But jQuery's ajax() method makes it possible to submit form, post and receive data without refreshing the page. Yep! A cool feature and so many modern websites use this technique to send & receive asynchronous HTTP request. And here we'll see how to use ajax in code igniter for form submission.

CodeIgniter Submit Form using AJAX Example:

Let's create a demo to submit form using ajax in codeigniter. As for this demo, consider you have a user subscription form with an input box for 'email id' and a 'subscribe' button - this is the form which you want to submit using ajax.

submit-form-using-ajax-in-codeigniter-example

First we'll need to create a controller for the demo and this would be it.

Controller: "ajax_demo.php"

<?php
class ajax_demo extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form','url'));
        $this->load->library('form_validation');
    }
    
    // load codeigniter view
    function index(){
        $this->load->view("ajax_demo_view");
    }
    
    // fn to which form 'll be submitted via ajax
    function submit()
    {
        //set validation rule
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email);
        
        if ($this->form_validation->run() == FALSE)
        {   
            //validation fails
            echo validation_errors();
        }
        else
        {
            // get post data
            $emailid = $this->input->post('email');
            
            // write your database insert code here
            ...
            
            echo "<div class='alert'>Thanks for Subscribing! Please stay tuned to get awesome tips...</div>";
        }
    }
?>

Next we have to create view for the controller and add a form & other necessary elements. Then you should include jquery library and add js snippet which will collect the form data (in our case it's just email id) and submit the form via jquery's ajax() method.

View: "ajax_demo_view.php"

<html>
    <head>
        <title>Codeigniter AJAX form Submission Demo</title>
    </head>
    <body>
        ...
        
        <script src="<?php echo base_url("/path/to/jquery-1.10.2.js"); ?>" type="text/javascript"></script>

        <script type="text/javascript">
        $("#submit").click(function(e) {
            e.preventDefault();
            var email_id = $("email").val();
            $.ajax({
                url: "<?php echo site_url('ajax_demo/submit'); ?>",
                method: "POST",
                data: {email: email_id},
                success: function(data) {
                    $("#message").html(data);
                },
                error: function() {
                    alert("Please enter valid email id!");
                }
            });
        });
        </script>

    </body>
</html>

In the above code, #submit specifies the id of the subscribe button and when it is clicked by user, the javascript will be executed and then form data will be submitted using ajax() without refreshing the page.

jQuery's ajax() function contains several options and we have used some of them in our example. Here are the descriptions for what those options stands for.

  • url - contains the URL to which the HTTP request is sent. (in our example, ajax_demo is the controller name and submit is the function to which we submit the form.)
  • method - specifies if the request is GET or POST.
  • data - contains the form data as json format. It can either be a string or object.
  • success - this function will be executed when the http request succeeds.
  • error - and this function will be invoked if the http request fails.

Submitting codeigniter form using ajax would be similar to submitting it with normal submit button. The only difference would be, that you have to load jquery library in codeigniter view and use it's ajax() or post() method to submit the form without refreshing the page. Like any other form, it will be submitted to the controller function and you have to specify it with URL option.

Related Read: CodeIgniter AJAX Form Example with Validation

So that explains how to submit form using ajax in codeigniter. I hope you find post this useful. Stay tuned for more interesting coding tutorials & tips.

1 comment: