CodeIgniter: jQuery $.ajax goodness

I’ve been using the jQuery JavaScript library for sometime now. It actually makes writing client-side programming fun, wow! The AJAX functionality is a joy to use; you can submit requests as POST instead of GET since the former is not available in the CodeIgniter PHP framework.

Say you have a controller user.php and a view user_add.php. Now you want to submit an AJAX request to the server to check if the (presumably unique) username field is available for use.


$(document).ready(function() { // user_add.php
	$('#username').blur(function() {
		$.ajax({
			url: 'username_callback/' + $(this).val(),
			type: 'post',
			success: function(result) {
				$('#username_check').attr('innerHTML', result);
			}
		});
	});
});

// html: user_add.php


So we’ve added an anonymous function to the username element. When it loses focus, we’ll submit a POST request to your your user controller, username_callback method. On success, we’ll replace the content (innerHTML) of the span username_check with the value returned by the PHP function.

I’m using the site_url() helper function to get my CI installation URL. NOTE: You’ll need to include this in the user.php constructor or in the autoloader.

// php: user.php

class User extends Controller
{
	function User()
	{
		parent::Controller();
		$this->load->helper('url');
	}

	function username_callback()
	{
		$s = trim(strip_tags($_POST['username'])); // clean

		if ($s == 'admin') { // error
			print 'The username 'admin' is reserved.'
		}
	}
}

username_check() will check if the POST-ed parameter is ‘admin’, and complain if so. So there you have it. That wasn’t too difficult, wasn’t it?

P.S. I would have loved to post up a working example but WP won’t accept .zip files.

#codeigniter, #jquery