In this small article I’ll show use how to send an email from your CodeIgniter website without submitting a form and reloading the page, but using Ajax to call a controller method and get instantly the response in your page.
Setting up CodeIgniter part.
If you are reading this, I suppose you already know what CodeIgniter is and how it works (otherwise you can start to learn here). I assume also you have your own domain and a CodeIgniter application already installed. In this small tutorial we’re going to use a bunch of files:
- the controller Main
- the views start_view and contact_view
- CodeIgniter configuration files config.php and route.php
Configuration files
First be sure that in your config/config.php file the variable $config[‘base_url’] be set correctly to your domain. If your domain is www.mydomain.com then in the config file we’ll have:
$config['base_url'] = 'http://www.mydomain.com/';
As you know, CodeIgniter allows you to use a really comfortable method to write your links: base_url() method:
<a href="<?php echo base_url('contacts') ?>">Contacts</a>
Now we can open application/config/route.php file to do some change. I’ll assume that our controller will be the default controller in our app, so in route.php file we’ll have to setup correctly the value of the variable $route[‘default_controller’]. In addition we have to add a line to manage our contact page link:
$route['default_controller'] = 'Main'; $route['404_override'] = ''; $route['contacts'] = 'Main/contacts';
The controller
In our controller we have only index method which load the start_view:
public function contacts() { $this->load->view( 'start_view' ); }
In the start_view we’ll just display a link to our contact form. I confess you’ll find very poor the style of these pages, but we have to focus on underlying code, isn’t it?
In Main controller we have to manage also the loading of the contact view and the method which actually sends our emails. The complete controller scripts looks like this one:
<?php if (!defined('BASEPATH')) { exit('No direct script access allowed'); } class Main extends CI_Controller { public function index() { $this->load->view( 'start_view' ); } public function contacts() { $this->load->view( 'contacts_view' ); } public function sendemail() { $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $to = 'mailbox@mydomain.com'; $subject = 'New message from your website'; $headers = "From: " . strip_tags($email) . "\r\n"; $headers .= "Reply-To: ". strip_tags($email) . "\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; if (mail($to, $subject, $message, $headers)) { echo 'Your message has been correctly sent. Thank you for contacting us: we'll reply as soon as possible<br><h4 style="text-align: right;">Lo Our staff</h4>'; } else { echo 'Ooops, I'm sorry but something went wrong sending your message. Please contact us at this address: '.safe_mailto( support@yourdomain.com ); } } }
As you can see, there’s nothing special: the method contacts() loads the contact view which displays a form to sen emails: when the user cliks the Send button the method sendemail() actually sends an image and echoes a message accordingly. This method is not reached by CodeIgniter through the routing system after a form submission: it’s instead called by jQuery through an Ajax call: this is the reason why this method doesn’t load any view: the view remain the current one, that is contact_view.
The views
This one is the interesting part, but let me quickly introduce our views. The first is start_view, the one that is loaded when we enter the site visiting thhe url www.mydomain.com
The start_view:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Send email Start page</title> </head> <body> <h1>The start view</h1> <p>If you don't like this page you can notify me using our <a href="<?php echo base_url('contacts'); ?>">contacts</a> page.</p> </body> </html>
I suspect we’re going to get a lot of emails…
The contacts_view:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Send email Start page</title> </head> <body> <h1>The contact view</h1> <p>Use the form to send us an email:</p> <div id="response"></div> <form> <label for="email">Email</label> <input id="email" type="text" placeholder="Email" /> <br> <label for="name">Nome</label> <input id="name" type="text" placeholder="Name" /> <br> <textarea id="message" placeholder="Your message here..."></textarea> <br> <button id="send"> Send </button> </form> </body> </html>
Notice the div with id set to “response” where the message returned by the controller will be displayed.
And, yes, the form is horrible, I know…
And now let’s send an email with Ajax…
We’re finally ready to implement our Ajax code to send email from our CodeIgniter website.
Stay on contacts_view: here we’re going to add our javascript code. First, we include jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Secondly, we must to let know jQuery something about our base url, so we’ll create a variable called baseUrl to use in opur script:
<script type="text/javascript"> var baseUrl = "<?php print base_url(); ?>"; </script>
And finally we can go with tha actual Ajax call:
$( document ).on( 'click', '#send', function ( e ) { e.preventDefault(); //hide response if it's visible $( '#response' ).hide(); //we grab all fields values to create our email var name = $( '#name' ).val(); var email = $( '#email' ).val(); var message = $( '#message' ).val(); if ( name === '' || email === '' || message === '' ) { //all fields are rquired so if one of them is empty the function returns return; } //if it's all right we proceed $.ajax( { type: 'post', //our baseurl variable in action will call the sendemail() method in our default controller url: baseurl + 'sendemail', data: { name: name, email: email, message: message }, success: function ( result ) { //Ajax call success and we can show the value returned by our controller function $( '#response' ).html( result ).fadeIn( 'slow' ).delay( 3000 ).fadeOut( 'slow' ); $( '#name' ).val( '' ); $( '#email' ).val( '' ); $( '#message' ).val( '' ); }, error: function ( result ) { //Ajax call failed, so we inform the user something went wrong $( '#response' ).html( 'Server unavailable now: please, retry later.' ).fadeIn( 'slow' ).delay( 3000 ).fadeOut( 'slow' ); $( '#name' ).val( '' ); $( '#email' ).val( '' ); $( '#message' ).val( '' ); } } ); } );
That’s all: it takes longer to say than to do.
Hope you’ll find useful this article and feel free to leave comments, criticism or everything you want to say… almost everything 😉
This is really helpful, thanks.
I found really helpful. I implemented this code in my website https://esegateconepts.in
Its really working great,..
Thank buddy!