If you want to get your hands dirty doing something a little harder then I suggest you check out my earlier blog on creating a login system with CodeIgniter.
If you are just getting started, have a look at my other blog posts, 'Ubuntu, LAMP and CodeIgniter' and the 'Extended JQuery Tutorial'.
Getting started
I am going to assume that you are working with a fresh installation of CodeIgniter that simply displays the welcome message. I am going to start from there so we don't get into any confusion!First, unzip the CodeIgniter source into your web-server's root directory (if you followed my LAMP guide above, this will default to /var/www/). Rename the extracted folder to test (so in the default example, the CodeIgniter framework will be stored in /var/www/test/).
Now delete ALL the php files in /var/www/test/application/controllers and /var/www/test/application/views. We are going to start completely fresh!
The final step is to configure the framework to use our new controller (once we create it...), so edit the file /var/www/test/application/config/routes.php with the following line:
$route['default_controller'] = "home";Now to make our main controller....
The Home page controller
- Create a file in /var/www/test/application/controllers named home.php
- Add in the following code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
/**
* Index Page for the home controller.
*
* Maps to the following URL
* http://example.com/index.php
* - or -
* http://example.com/index.php/home
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/home/<method_name>
* @see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->view('view');
}
}
/* End of file ajax.php */
/* Location: ./application/controllers/home.php */ - That's it. All this does is load up our view, which is our next step.
The Home page view
- Create a file in /var/www/test/application/views named view.php
- Add in the following code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Test</title>
<!-- JQuery code hosted by Google -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<!-- Adding and Deleting form buttons -->
<script type="text/javascript" src="form.js"></script>
<!-- AJAX functionality -->
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
<form id="myForm">
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
Name: <input type="text" class="name" name="name1" id="name1" />
</div>
<div>
<input type="button" id="btnAdd" value="add another name" />
<input type="button" id="btnDel" value="remove name" />
<input type="button" name="submit" class="button" id="submit" value="Send" />
</div>
<div id="display">
</div>
</form>
</body>
</html> - Our basic HTML page includes three JavaScript files (One is the JQuery API, the other two we write ourselves; see below). We have a form with an input text box and three buttons. The first two buttons add and remove input boxes from our form, while the last button performs our AJAX operation.
form.js - Dynamically adding form elements
- Create a file called form.js in /var/www/test/
- Add the following code:
$(document).ready(function() {
$('#btnAdd').click(function() {
// how many "duplicatable" input fields we currently have
var num = $('.clonedInput').length; // the numeric ID of the new input field being added
var newNum = new Number(num + 1);
// create the new element via clone(),
// and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled','');
// business rule: you can only add 5 names
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
// how many "duplicatable" input fields we currently have
var num = $('.clonedInput').length;
// remove the last element
$('#input' + num).remove();
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
}); - This function attaches a JavaScript function to the add and remove button. The code is pretty well commented by Charlie Griefer, so if you want to know more I suggest you go visit his blog post.
ajax.js - AJAX with JQuery
- Create a file called ajax.js in /var/www/test/
- Add the following code:
$(document).ready(function() {
// This will run when the item of id 'submit' is clicked
$("#submit").click(function() {
// Grabs the text input from the form
var name = [];
$(".name").each(function() { name.push($(this).val()) });
// Create the key-value pair for POST
var dataString = 'string=' + name.join(' ') + '';
// This creates the AJAX connection
$.ajax({
type: "POST",
url: "index.php/ajax",
data: dataString,
dataType: 'json',
success: function(obj) {
$('#display').html(obj.message);
}
});
return false;
});
}); - This will send all of our dynamically generated form elements to index.php/ajax (which we will now create). Hopefully the code and comments are self explanatory; if you have any problems just shout out in the comments!
The AJAX controller
- Create a file in /var/www/test/application/controllers named ajax.php
- Add the following code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajax extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/ajax
* - or -
* http://example.com/index.php/ajax/index
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/ajax/<method_name>
* @see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$txtValue = "We have recieved: " . $this->input->post('string');
echo json_encode(array('message' => $txtValue));
}
}
/* End of file ajax.php */
/* Location: ./application/controllers/ajax.php */ - You should now be able to run this on your web-server and have a dynamic form that sends and recieves AJAX!
References:
- 'Dynamically adding form elements' by Charlie Griefer
- My post on AJAX, JQuery and PHP
- Refresh-less form validation from NetTutes
- Tutorial from PHP4Every1