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:
- 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).
- 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.
- Get rid of index.php from url's using .htaccess, best tutorial that I've found: CI .htaccess.
- 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(example.com/this_section). I am making one called form, that looks like:This already includes CodeIgniter libraries that we are going to use.Source code viewer
<?php class Form extends Controller { function __construct() { //<-PHP5 - __construct(); PHP4 - form() parent::Controller(); $this->load->helper('form'); //functions that allow making forms faster $this->load->library('form_validation'); //class for form validation $this->load->helper('url'); //includes function base_url() } function index() { } } /* End of file form.php */ /* Location: ./system/application/controllers/form.php */Programming Language: PHP (brief)
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
function index() { //The parameters are: inputs name, field name for human eye, rules $this->form_validation->set_rules('name', 'Name', 'trim|required|max_length[50]|xss_clean'); $this->form_validation->set_rules('email, 'Email Address', 'trim|required|valid_email|callback_unique_email'); $this->form_validation->set_rules('message', 'Message', 'required'); if($this->form_validation->run() === FALSE) { //happens on load and failiour } else { //happens on success } }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
if($this->form_validation->run() === FALSE) { //if errors come then don't print the form //on load print the form else echo '<html><head>', //Load css and js files, don't forget to change file names and directories '<link type="text/css" href="',base_url(),'css/design_name_you_picked/jquery-ui-1.8.custom.css" rel="Stylesheet" />', '<script type="text/javascript" src="',base_url(),'js/jquery-1.4.2.min.js"></script>', '<script type="text/javascript" src="',base_url(),'js/jquery-ui-1.8.custom.min.js"></script>', '</head><body>', //javascript/ajax part '<script type="text/javascript">$(document).ready(function($){', '$("input:submit","#contact_us").button();', //Make the submit putton look nice(jQuery UI) '$("#contact_us").submit(function(){$.post(', //on button press send data by post '"/form",', //submition dir '$("#contact_us").serialize(),function(data){', //return results '$("#errors").empty();$("#errors").append(data);', //Here goes error/success messages after submit '});return false;});});</script><div id="errors"></div>', //generate the form, 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 form_label('Name: ', 'name'),'<br />',form_input('name'),'<br /><br />', form_label('Email Address: ', 'email'),'<br />',form_input('email'),'<br /><br />', form_label('Subject: ', 'subject'),'<br />',form_input('subject'),'<br /><br />', form_label('Message: ', 'message'),'<br />',form_input('message'),'<br /><br />', form_close(),'</body></html>'; } else { //Here goes the code what do you do on success, send e-mail or write data to database. }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 likeSource code viewer
$this->validation->set_error_delimiters('before error', 'after error');Programming Language: PHP (brief)
Here is the helper:
Source code viewer
//$msg - error message; function ajax_error_msg($msg) { return '<div class="ui-widget" style="margin:0 0 2px 0;font-size:12px">'. '<div class="ui-state-error ui-corner-all" style="padding:5px 9px">'. '<span class="ui-icon ui-icon-alert" style="float:left;margin-right:.3em"></span>'. '<strong>Error:</strong> '.$msg. '</div>'. '</div>'; } } //$msg - error message; function ajax_success_msg($msg) { return '<script type="text/javascript">$("input:password,input:text,textarea").val("");</script>'. '<div class="ui-widget" style="margin:0 0 2px 0;font-size:12px">'. '<div class="ui-state-highlight ui-corner-all" style="padding:5px 9px">'. '<span class="ui-icon ui-icon-info" style="float:left;margin-right:.3em"></span>'. '<strong>Success:</strong> '.$msg. '</div>'. '</div>'; } } /* End of file error_helper.php */ /* 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.