CodeIgniter MODAL Contact Form w/ jQuery AJAX Validation Example

On 9/14/2015

Hi, a while back I have written a tutorial about building contact form in codeigniter. It got great feedbacks and some of the readers asked about implementing the same feature in modal popup form. I thought it would be beneficial to kodingmadesimple.com readers if I provide it as a separate tutorial and in this article I’m going to show you How to Build a Proper Modal Contact Form in CodeIgniter with AJAX Field Validations.

Though the features of the modal form we are going to build would be similar to regular contact form, it become little bit tricky in the way we do form field validations. Since we can’t afford to refresh the page by submitting the form, we should go by AJAX technique to avoid page refreshing.

One thing to mention here is I wish to validate the form input on server side for security reasons even though you can do it on client side. Let’s see how to implement this in codeigniter.

Recommended Read: How to Get User IP Address in CodeIgniter

Creating Modal Form using Twitter Bootstrap CSS

To build our modal form, we are going to use Twitter Bootstrap CSS since it provides easy-to-use modal component and it fits our purpose. In order to use bootstrap in codeigniter you have to properly integrate the two frameworks. It’s very simple to do it and if you don’t know how, read this article to setup bootstrap css in codeigniter framework.

CodeIgniter Modal Contact Form Workflow

Modal Form is just like any other web forms but it opens up as a popover, so it should be invoked by clicking a button or a link. For better understanding I’ll show this with an example page, consisting a top navigation menu with ‘Contact’ menu link and upon clicking the contact menu the modal contact form should pop up.

Then using the ajax technique we should post the form data, run validation check and display if there are any validation errors at the bottom of the form. If it passes validation check, we should configure and send email to the site owner’s email address and provide proper message alerts to the user.

Implementing Modal Contact Form in CodeIgniter

To implement the modal form we should create a controller and a view file (for interface) in codeigniter. Since we are going to process the form data and send it as email there is no need for model file.

The Controller File (‘modal_contact.php’)

First create a file named ‘modal_contact.php’ inside ‘application/controllers’ folder and copy paste the below code to it.

<?php
class modal_contact extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form','url'));
        $this->load->library(array('form_validation', 'email'));
    }

    function index()
    {
        $this->load->view('modal_contact_view');
    }

    function submit()
    {
        //set validation rules
        $this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean|callback_alpha_space_only');
        $this->form_validation->set_rules('email', 'Emaid ID', 'trim|required|valid_email');
        $this->form_validation->set_rules('subject', 'Subject', 'trim|required|xss_clean');
        $this->form_validation->set_rules('message', 'Message', 'trim|required|xss_clean');
        
        //run validation check
        if ($this->form_validation->run() == FALSE)
        {   //validation fails
            echo validation_errors();
        }
        else
        {
            //get the form data
            $name = $this->input->post('name');
            $from_email = $this->input->post('email');
            $subject = $this->input->post('subject');
            $message = $this->input->post('message');
            
            //set to_email id to which you want to receive mails
            $to_email = 'user@gmail.com';
            
            //configure email settings
            $config['protocol'] = 'smtp';
            $config['smtp_host'] = 'ssl://smtp.gmail.com'; // change this to yours
            $config['smtp_port'] = '465';
            $config['smtp_user'] = 'user@gmail.com'; // change this to yours
            $config['smtp_pass'] = 'velmayil'; // change this to yours
            $config['mailtype'] = 'html';
            $config['charset'] = 'iso-8859-1';
            $config['wordwrap'] = TRUE;
            $config['newline'] = "\r\n"; //use double quotes
            $this->email->initialize($config);
            
            //send mail
            $this->email->from($from_email, $name);
            $this->email->to($to_email);
            $this->email->subject($subject);
            $this->email->message($message);
            if ($this->email->send())
            {
                // mail sent
                echo "YES";
            }
            else
            {
                //error
                echo "NO";
            }
        }
    }
    
    //custom validation function to accept alphabets and space
    function alpha_space_only($str)
    {
        if (!preg_match("/^[a-zA-Z ]+$/",$str))
        {
            $this->form_validation->set_message('alpha_space_only', 'The %s field must contain only alphabets and space');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
}
?>

The constructor function loads the essential helper & libraries including the ‘email’ class for sending mail.

The index() function is the default one to be called when we invoke the controller and it loads the view file (this we will create next) to show the form interface.

The submit() function is where the form data is posted through ajax call, run validation check and send email.

Here we set the validation rules for all the form fields and run validation check. If there is any validation error then we display it at the bottom of the form. The statement echo validation_errors(); will return back all the validation error messages. This in turn will be received by the jquery ajax function and displayed at the bottom of the modal form interface like this.

codeigniter-ajax-form-validation-example
CodeIgniter AJAX Form Validation Errors

If there is no such validation errors, then we configure the email settings and send the mail using $this->email->send(); statement. We also notify the user if their message is properly sent or not.

The View File (‘modal_contact_view.php’)

Now it’s time to create the modal interface. Create a file named ‘modal_contact_view.php’ inside ‘application/views’ folder and copy paste the below code and save.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeIgniter Modal Contact Form Example</title>
    <!--load bootstrap css-->
    <link href="<?php echo base_url("assets/bootstrap/css/bootstrap.css"); ?>" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- Navigation Menu -->
<nav class="navbar navbar-inverse" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar1">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">ShopMania</a>
        </div>
        <div class="collapse navbar-collapse" id="navbar1">
            <ul class="nav navbar-nav">
                <li><a href="#">Home</a></li>
                <li><a href="#">About</a></li>
                <li><a href="#">Deals & Offers</a></li>
                <li><a href="#">Blog</a></li>
                <li class="active"><a href="#" data-toggle="modal" data-target="#myModal">Contact</a></li>
            </ul>
        </div>
    </div>
</nav>

<!-- modal form -->
<div id="myModal" class="modal fade" aria-labelledby="myModalLabel" aria-hidden="true" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <?php $attributes = array("name" => "contact_form", "id" => "contact_form");
            echo form_open("modal_contact/submit", $attributes);?>

            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title">Contact Form</h4>
            </div>
            <div class="modal-body" id="myModalBody">
                <div class="form-group">
                    <label for="name">Name</label>
                    <input class="form-control" id="name" name="name" placeholder="Your Full Name" type="text" value="<?php echo set_value('name'); ?>" />
                </div>
                
                <div class="form-group">
                    <label for="email">Email ID</label>
                    <input class="form-control" id="email" name="email" placeholder="Email-ID" type="text" value="<?php echo set_value('email'); ?>" />
                </div>

                <div class="form-group">
                    <label for="subject">Subject</label>
                    <input class="form-control" id="subject" name="subject" placeholder="Subject" type="text" value="<?php echo set_value('subject'); ?>" />
                </div>

                <div class="form-group">
                    <label for="message">Message</label>
                    <textarea class="form-control" id="message" name="message" rows="4" placeholder="Message"><?php echo set_value('message'); ?></textarea>
                </div>

                <div id="alert-msg"></div>
            </div>
            <div class="modal-footer">
                <input class="btn btn-default" id="submit" name="submit" type="button" value="Send Mail" />
                <input class="btn btn-default" type="button" data-dismiss="modal" value="Close" />
            </div>
            <?php echo form_close(); ?>            
        </div>
    </div>
</div>
<!--load jquery & bootstrap js files-->
<script type="text/javascript" src="<?php echo base_url("assets/js/jquery-1.10.2.js"); ?>"></script>
<script src="<?php echo base_url("assets/bootstrap/js/bootstrap.min.js"); ?>"></script>
<script type="text/javascript">
$('#submit').click(function() {
    var form_data = {
        name: $('#name').val(),
        email: $('#email').val(),
        subject: $('#subject').val(),
        message: $('#message').val()
    };
    $.ajax({
        url: "<?php echo site_url('modal_contact/submit'); ?>",
        type: 'POST',
        data: form_data,
        success: function(msg) {
            if (msg == 'YES')
                $('#alert-msg').html('<div class="alert alert-success text-center">Your mail has been sent successfully!</div>');
            else if (msg == 'NO')
                $('#alert-msg').html('<div class="alert alert-danger text-center">Error in sending your message! Please try again later.</div>');
            else
                $('#alert-msg').html('<div class="alert alert-danger">' + msg + '</div>');
        }
    });
    return false;
});
</script>
</body>
</html>

The <nav> element creates responsive navigation menu using bootstrap’s navbar component. Next we have created the modal form with id #myModal and invoke it using the data attribute data-target="#myModal" when the user clicks on the ‘contact’ menu.

At the bottom of the markup we have created a jQuery script to run when the user clicks on the ‘Send Mail’ button and it collects the form data and post it to the controller’s submit() function. The return value is received and the appropriate message alerts are displayed on the div block with id #alert-msg.

That’s it. We have completed the coding part. Now run the controller in the browser and you can see a page with navigation menu like this.

twitter-bootstrap-navigation-menu-example

Next click on the ‘Contact’ menu link and the modal form pops up like this.

codeigniter-modal-contact-form-ajax-validation-example
CodeIgniter Modal Contact Form

When you feed the form data and click on the ‘Send Mail’ button, the form data is submitted and processed via AJAX call and appropriate success or failure alerts will be displayed like this.

codeigniter-send-email-success-message
codeigniter-send-email-failure-message

Now we have created a working modal contact form in php codeigniter framework. If you want to store the contact form data into database rather than sending mail, then read this codeigniter contact form tutorial with database storage option.

Also Read:

9 comments:

  1. Another great post/tutorial Valli!
    To take it a step further, what would one need to do to implement additional code that would reset/clear the form, disable the 'Send' button, close the modal window, or all three upon successful submission? Thanks!!!

    ReplyDelete
    Replies
    1. Hi! Use $('#contact_form')[0].reset(); to clear form inputs after successful mailing. If you want to close the modal altogether, then use it with alert box like this,

      ...
      success: function(msg) {
      if (msg == 'YES')
      {
      alert('Your mail has been sent successfully!');
      $('#contact_form')[0].reset();
      $('#myModal').modal('hide');
      }
      ...
      }
      ...

      Hope this helps! Cheers :-)

      Delete
  2. How to slow done the time of alert message

    ReplyDelete
    Replies
    1. you can delay the execution with sleep(2); The process will delay by 2 seconds here.

      Delete
  3. Great tutorial I am using it to implement modal form that submits to db but am getting errors, can you help me out? This is the link http://stackoverflow.com/questions/37396146/passing-data-on-a-bootstrap-model-and-submitting-to-db-with-code-ignitor
    Thanks.

    ReplyDelete
  4. awesome tutorial. I'm integrating this into an old project. problem is, in my view I'm not displaying all the validation error messages at the bottom, I'm displaying each error message below their individual input field, with echo form_error('the_field_name'); how should I modify your controller/view to achieve this?

    ReplyDelete
  5. send mail button does not work

    ReplyDelete
  6. Awesome tutorial dont see where i went wrong but the send button doesnt work

    ReplyDelete
  7. is that possible to use the form_error ? i would like to write the error just below the field.

    ReplyDelete

Contact Form

Name

Email *

Message *