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() {
			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()

	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.

20 thoughts on “CodeIgniter: jQuery $.ajax goodness

  1. Hey – This looks great, but i have a few questions.
    1. Can you email me a copy of your files?
    2. I don’t see any DB connection info here…perhaps you can elaborate a little bit. This is the first and only ‘tutorial’ on jquery and code igniter that i’ve found so far…

  2. hello,

    I ‘m new to code igniter and jquery. The above example is great. Can you please email me the working example of yours so that i could get a clear understanding.


  3. I’m a bit of a CI & JQuery noob too, so please forgive me if I’ve missed the obvious but should the function in user.php be called username_callback() or username_check().

    I’m struggling to see how username_callback gets called…

  4. Hey Wayne, I think Martin may have a point here…
    if you set

    rules[‘username’] = ‘callback_username_check’;

    then the function in user.php should be username_check()

    Moreover, given that it’s coming back through Ajax, doesn’t the URL at least have to be:

    if we are going to find the main user function?

  5. oops, it stripped my php
    “doesn’t the URL at least have to be:
    (php) site_url . ‘/user/’
    if we are going to find the main user function?”

  6. Yes WordPress strips the PHP code. You’ll need to use the URL helper, and pass it as a string so jquery knows which URL to callback on the username Javascript event.

  7. You need to put the .js file somewhere, may I suggest public/javascript/ from the CodeIgniter base directory. So you should have ‘index.php’, ‘license.txt’ and ‘public’. And then of course refer to the external jquery like here.

  8. Is there a reason why you are using $_POST instead of code igniters built in input library, ie. $something = $this->input->post(‘something’);


    1. Well CodeIgniter users will understand both. The rest of ’em might not, you see.

      Another reason I can think of is when you want to perform a loop:

      foreach ($_POST as $k => $v) {
      $v = $this->input->post($k, true); // xss cleaned

      So $_POST array values are never used, I just want the name to reference it when using CI’s $this->input->post().

  9. Hi Wayne,i still don’t understand how to get Jquery works with CI..Suppose in my views i gor codes like this..

    echo form_open_multipart('admin/produk/create');
    echo "Category”;
    echo form_dropdown(‘cat_id’,$categories) .””;

    echo “Name”;
    $data = array(‘name’=>’nama’,’id’=>’nama’,’size’=>25);
    echo form_input($data) .””;

    echo “Short Description”;
    $data = array(‘name’=>’shortdesc’,’id’=>’short’,’size’=>40);
    echo form_input($data) .””;

    echo “Long Description”;
    $data = array(‘name’=>’longdesc’,’id’=>’long’,’rows’=>5, ‘cols’=>’40’);
    echo form_textarea($data) .””;
    echo form_submit(‘submit’,’create product’);
    echo form_close();

    Where should i put the js?And also how to load the js?Thanks a lot wayne..

  10. hi, I refer the following link as you stated. Demo site is performing well. But when I applied it into my own work, I always face problem in remote there, cannot pass the data to user.php page. Do you mind to explain to me? I am using codeIgniter platform. Much appreciate if you can help me.
    Thank you

  11. I notice that using JavaScript, your controller paths and functions are exposed. How would you stop someone from directly going into the callback function by typing in “”? I’d only want it to be accessible through the Javascript. I don’t want this to happen in my site and leave other people to hack around unnecessarily.

    1. But well, it doesn’t matter. As long as your server is turned on and links to various pages served by your system are available, you are exposing your site. But I digress.

      To prevent users from accessing a URL intended for AJAX consumption, you could perhaps use a function below that is executed in username_callback, and serving up no content when false is returned.

      function isAjax() {
      return env(‘HTTP_X_REQUESTED_WITH’) === “XMLHttpRequest”;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s