CodeIgniter MODAL Contact Form w/ jQuery AJAX Validation Example

CodeIgniter MODAL Contact Form w/ jQuery AJAX Validation Example


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 tokodingmadesimple.com readers if I provide it as a separate tutorial and in this article I’m going to show youHow 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.
codeigniter-modal-contact-form-jquery-ajax-validation
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.

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

4 comments:

  1. Great insights! I really appreciate how clearly you’ve outlined the topic. Your post has provided some valuable clarity. Thanks for sharing!

    ReplyDelete
  2. Create a CodeIgniter contact form that uses jQuery AJAX for submission and validation by setting up the form in your view, creating a controller HostMyCode method to handle the AJAX request, and using jQuery to validate and send the data asynchronously.

    ReplyDelete