​Using Ajax in CodeIgniter

Marco GasiFreelancer
CERTIFIED EXPERT
Freelance, I like to share what I know. Find out my articles in my learner-to-learners blog https://codingfix.com
Published:
Updated:
In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
When I started to move my small CMS to CodeIgniter, one of the first problems I found has been how to implement Ajax calls within the MVC pattern.
 
I discovered that it's quite a simple thing and here I show you how to do it. 

To make the example more interesting, I'll show you how to build a form to allow your user to send you an email, something we all always need. To do it, I'll use CodeIgniter 2.2 (don't worry, the same rules will work with CI 3 if you respect the new rules, overall to capitalize all class file names) and jQuery.
 
The main problem when you want to use Javascript with CI is the CI url structure. As you know, when you have to write a link to a page within a CodeIgniter view, you have to use base_url() method, which returns the root of your site as you have configured it in the config.php.

So, if your site is www.example.com, we can reasonably expect you have in your config.php file the following line:

 

$config['base_url'] = 'http://www.example.com/';


This means that in your view, to build a link to the contact page you'll have to write

 

<a href="<?php echo base_url('contacts') ?>">Contacts</a>


But your javascript knows nothing about base_url() and of course you can't use a plain absolute path to link your script in an Ajax call because this just doesn't work: once filtered by CI, the Ajax call is missing like an echo in a desert.

So, the first we have to do is to make base_url available for our javascript. Open your footer view (tipically 'footer_view.php') and add following lines:

 

<script type="text/javascript">
    var baseurl = "<?php print base_url(); ?>";
</script>



In this case, we'll use a specific javascript file to perform our action and we'll call it sendmail.js (what a fantasy, uh?). So our footer view will look like this one:

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="<?php echo base_url('assets/js/app.js'); ?>"></script>
<script type="text/javascript">
    var baseurl = "<?php print base_url(); ?>";
</script>


Now, our sendmail.js knows about base_url() all of what it needs to know, so it'll work like a charm.

This done, we can proceed, starting by the email form. When the user clicks on the link to open the contact page, the controller method called contacts() load contact_view.php with its header and footer. Take a look at the form:

 

<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>


Well, it doesn't look too nice, but it's just a raw form for our example: making it nice is up to you :-) The only thing I want you notice is the div I placed immediately before the form: it'll hold a success or an error message returned by the method which actually will send our email.

As you can see, there's no action, no method, no submit: all stuff will be managed by jQuery. Let's go there, now.

 

$( 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 a method in our default controller
        url: baseurl + 'sendmail',
        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( '' );
        }
    } );
} ); 


As promised, the code is quite simple. Let me just remind you that the success and error function within the Ajax call are not referred to the sending email action but only to the Ajax call: in other words, the error means the call failed probably because the script couldn't be found and the success means that the script has been reached successfully. So our Ajax call will return success even if the script fails sending our email. You have to keep in mind this when you write the messages that controller method sendmail() will return.


And now, let's see the method sendmail():

 

public function sendmail()
{
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $to = 'yourname@yourdomain.com';
    $subject = 'New message from your site';
    $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 I said before, you have to check if mail() function worked fine and return the appropriate message to your user: the message echoed here is the message that jQuery will make visible in div 'response' as result of the Ajax call.


Voilà: not too difficult, is it? And it works like a charm: add some css style to stylish the visible elements and you'll get a quick and easy way to implement a modern, Ajax email form. And overall, you can now easily add Ajax capabilities to your CodeIgniter site.

1
14,240 Views
Marco GasiFreelancer
CERTIFIED EXPERT
Freelance, I like to share what I know. Find out my articles in my learner-to-learners blog https://codingfix.com

Comments (1)

Marco GasiFreelancer
CERTIFIED EXPERT
Top Expert 2010

Author

Commented:
Well, I'm happy. But I've just realized that today is still May: will this article partecipate to the contest for the Blade-Runner HD?

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.