You are here

26 June 2010
Some knowledge of CI and OOP could be handy. This tutorial shows how to submit Ajax forms in CodeIgniter using jQuery. With optional jQuery UI feedback bubbles.
Setting up CodeIgniter and jQuery with jQuery UI:
  1. First of all get CodeIgniter and pick jQuery UI with your favorite color scheme. I am using versions 1.7.2 of CodeIgniter and 1.8.2 version of jQuery UI(and the jQuery version that came with it was 1.4.2).
  2. Upload CodeIgniter to some server, localhost is just fine(XAMPP for an example). If you haven't done this before, then I suggest to read how to do set CodeIgniter up from their user guide.
  3. Get rid of index.php from url's using .htaccess, best tutorial that I've found: CI .htaccess.
  4. Copy folders css and js folders from jQuery UI zip file to the root directory(where your system folder is). All things are set up and we can start setting up our form.

Making controller:

Make new controller to system>application>controllers. Controller is the part that controls first section of URL( I am making one called form, that looks like:
Source code viewer
  1. <?php
  2. class Form extends Controller {
  3. function __construct() { //<-PHP5 - __construct(); PHP4 - form()
  4. parent::Controller();
  5. $this->load->helper('form'); //functions that allow making forms faster
  6. $this->load->library('form_validation'); //class for form validation
  7. $this->load->helper('url'); //includes function base_url()
  8. }
  9. function index() {
  11. }
  12. }
  14. /* End of file form.php */
  15. /* Location: ./system/application/controllers/form.php */
Programming Language: PHP (brief)
This already includes CodeIgniter libraries that we are going to use.

Set up validation part of from into index():

I picked making of contact form, so I need Name, Email Address, Subject, Message fields. If you are making different form then you need different rules, for full list of rules check out CodeIgniters user guide, ofcourse you can make your own rules aswell. Next code shows how to set up rules for contact form.
Source code viewer
  1. function index() {
  2. //The parameters are: inputs name, field name for human eye, rules
  3. $this->form_validation->set_rules('name', 'Name', 'trim|required|max_length[50]|xss_clean');
  4. $this->form_validation->set_rules('email, 'Email Address', 'trim|required|valid_email|callback_unique_email');
  5. $this->form_validation->set_rules('subject', 'Subject', 'trim|required|max_length[60]|xss_clean');
  6. $this->form_validation->set_rules('message', 'Message', 'required');
  7. if($this->form_validation->run() === FALSE) {
  8. //happens on load and failiour
  9. }
  10. else {
  11. //happens on success
  12. }
  13. }
Programming Language: PHP (brief)

Create the HTML form with jQuery AJAX function:

I am making form by using functions from CodeIgniters form helper to speed up the process. The AJAX part is in the script tags. You should use views to store your html, but I am not going to use them here so everybody would understand what I am doing here. You can use different views for javascript/AJAX part and form part. So you can reuse the AJAX in all of your form.
Source code viewer
  1. if($this->form_validation->run() === FALSE) {
  2. //if errors come then don't print the form
  3. if(validation_errors() != '') echo validation_errors();
  4. //on load print the form
  5. else echo
  6. '<html><head>',
  7. //Load css and js files, don't forget to change file names and directories
  8. '<link type="text/css" href="',base_url(),'css/design_name_you_picked/jquery-ui-1.8.custom.css" rel="Stylesheet" />',
  9. '<script type="text/javascript" src="',base_url(),'js/jquery-1.4.2.min.js"></script>',
  10. '<script type="text/javascript" src="',base_url(),'js/jquery-ui-1.8.custom.min.js"></script>',
  11. '</head><body>',
  12. //javascript/ajax part
  13. '<script type="text/javascript">$(document).ready(function($){',
  14. '$("input:submit","#contact_us").button();', //Make the submit putton look nice(jQuery UI)
  15. '$("#contact_us").submit(function(){$.post(', //on button press send data by post
  16. '"/form",', //submition dir
  17. '$("#contact_us").serialize(),function(data){', //return results
  18. '$("#errors").empty();$("#errors").append(data);', //Here goes error/success messages after submit
  19. '});return false;});});</script><div id="errors"></div>',
  20. //generate the form,
  21. form_open('form', array('id' => 'contact_us')), //first parameter is the return point of form, tough we use ajax, people who don't have javascript might still want to submit the form
  22. form_label('Name: ', 'name'),'<br />',form_input('name'),'<br /><br />',
  23. form_label('Email Address: ', 'email'),'<br />',form_input('email'),'<br /><br />',
  24. form_label('Subject: ', 'subject'),'<br />',form_input('subject'),'<br /><br />',
  25. form_label('Message: ', 'message'),'<br />',form_input('message'),'<br /><br />',
  26. form_close(),'</body></html>';
  27. }
  28. else {
  29. //Here goes the code what do you do on success, send e-mail or write data to database.
  30. echo 'Message successfully sent';
  31. }
Programming Language: PHP (brief)

Pritty error and success boxes:

I am not going to make the code longer so I'm just giving you helper I made that includes two functions. You can read how to use helpers from CodeIgniters user guide. On success it's easy to use, but for automatic validation errors you have to edit the validation class or all the errors will be in the same bubble. If you are not using the helper then you can define error delimiters like
Source code viewer
  1. $this->validation->set_error_delimiters('before error', 'after error');
Programming Language: PHP (brief)

Here is the helper:
Source code viewer
  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. if (!function_exists('ajax_error_msg')) {
  3. //$msg - error message;
  4. function ajax_error_msg($msg) {
  5. return '<div class="ui-widget" style="margin:0 0 2px 0;font-size:12px">'.
  6. '<div class="ui-state-error ui-corner-all" style="padding:5px 9px">'.
  7. '<span class="ui-icon ui-icon-alert" style="float:left;margin-right:.3em"></span>'.
  8. '<strong>Error:</strong> '.$msg.
  9. '</div>'.
  10. '</div>';
  11. }
  12. }
  13. if (!function_exists('ajax_success_msg')) {
  14. //$msg - error message;
  15. function ajax_success_msg($msg) {
  16. return '<script type="text/javascript">$("input:password,input:text,textarea").val("");</script>'.
  17. '<div class="ui-widget" style="margin:0 0 2px 0;font-size:12px">'.
  18. '<div class="ui-state-highlight ui-corner-all" style="padding:5px 9px">'.
  19. '<span class="ui-icon ui-icon-info" style="float:left;margin-right:.3em"></span>'.
  20. '<strong>Success:</strong> '.$msg.
  21. '</div>'.
  22. '</div>';
  23. }
  24. }
  26. /* End of file error_helper.php */
  27. /* Location: ./system/application/helpers/error_helper.php */
Programming Language: PHP
You can notice that many things repeat. To get rid of that you can put fields data into array and use foreach to generate the fields, but I am trying to keep things as simple as possible. On some cases you might want to put the data into table, like login form. Again I'm trying to keep things simple.