Using XAJAX with CodeIgniter

November 20th, 2009

Let’s make a deal. All you want to do is get XAJAX working in CodeIgniter (CI) in less than the many hours it took me to figure it out, and all I want to do is get more traffic to my points of interest website www.poipedia.org.

So how about this. I’ll show you how to get XAJAX working with CodeIgniter, and in return, you head on over to poipedia.org and add a few of your favorite restaurants? Or better yet, download the free poipedia iphone app in iTunes and take pictures of your favorite places. Save a list of your favorite restaurants, and help us all find the good places to eat (and make poipedia look good on my resume).

Deal?

Seriously. Why else am I posting all this?

C’mon.

oh alright, i’ll show you the code first. this article looks long, but there’s really not much to it. don’t be scared, i’ve already done all the hard parts for you. in just a few minutes you’ll have xajax working.. you’ll be smiling.. and i’ll be hoping you’re kind enough to add something to poipedia.org, or e-mail me with a great web-site idea we can work on together.  here we go.

If you’re like me, you probably tried just including the php files per the learn xajax in 10 minutes docs and ended up getting some arcane error message in Firebug that reads “[Exception... "'[object Object]‘ when calling method: [nsIDOMEventListener::handleEvent]” nsresult: “0×8057001c (NS_ERROR_XPC_JS_THREW_JS_OBJECT)” location: “<unknown>” data: no] Line 0″

huh?  what am I supposed to do with that?  google turns up nothing… (which is why i’m adding it here)

hmm.. ok over to the CI docs on xajax and there’s an article ( http://codeigniter.com/wiki/XAJAX/ ) .  Perfect!

wait… what is that??  right there on the third line, that little “Note: This doc is obsolete”.  noooo!!

alright, maybe i can still pull this apart.. it kind of looks good, but it’s got a lot of what appears to be unecessary steps (like creating a library loader) and munging the view code into the controller.  i’d like to keep the view code in the view and i don’t need to be messing with library loaders.  let’s try something else:  XAJAX + CodeIgniter in 3… 2… 1…

Install XAJAX
into the funny CodeIgniter directory structure!

  1. Download XAJAX Standard here: http://xajaxproject.org/en/download/ At the time of this writing, the most recent release is 0.5, but it shouldn’t matter much.
  2. Unzip the zip file
  3. Upload the xajax_0.5_standard/xajax_core folder to /www/system/application/xajax_0.5_standard/xajax_core
  4. Upload the xajax_0.5_standard/xajax_js folder to /www/xajax_0.5_standard/xajax_js

I like to leave the version number in the folder names, otherwise, how will I remember a year from now if I need to upgrade?  Or what version to upgrade from?

Notice we had to put the xajax php code with the CI php code, and xajax looks for web stuff based on your url so we have to put it someplace web-accessible which is why we put it in our web root folder.  That’s the first tricky bit.  xajax is nice enough to pop up an error message letting you know if it can’t find the js files it needs (go xajax!  much appreciate that).  I had no need for the other xajax folders as I was just doing simple ajax requests, but i imagine that once you get this working, you can probably deduce where they might belong should a project require them.

Add XAJAX Include Paths
You don’t have to do this, but I did because I think it makes upgrading to a later version of xajax that much easier. I defined the path in a constant by creating a util directory and constants.php file at /www/system/application/util/constants.php with the following code:

<?php
define ("XAJAX_FOLDER", "xajax_0.5_standard");
define ("XAJAX_PHP", APPPATH . XAJAX_FOLDER . '/xajax_core/xajax.inc.php');

I didn’t close my php tag on purpose. You shouldn’t close your php tags. Remember that for your next job interview. ;)

When I upgrade xajax later, all I’ll have to do is upload the new version, and change the XAJAX_FOLDER define and not touch any code.

Add XAJAX to the Controller

Pick a controller.. any controller.  You can have a special ajax controller, or I would recommend picking the controller for your view (makes sense right?  a view requires ajax and its ajax requests are sent to its controller).

Add a constructor to the controller which will initialize xajax.  For poipedia I have a controller class View defined in CI at controllers/view.php.  The beginning of that controller looks like this:

<?php
 
require_once(APPPATH . 'util/constants.php');
 
require_once(XAJAX_PHP);
 
class View extends Controller {
 
 
	private $xajax = '';
 
    function View() {
        parent::Controller();
        $this->xajax = new xajax();
        $this->xajax->registerFunction(array('addFavorite',&$this,'addFavorite'));
        $this->xajax->processRequest();
    }
 
    function addFavorite()
    {
        // Instantiate the xajaxResponse object
        $objResponse = new xajaxResponse();
        // add a command to the response to assign the innerHTML attribute of
        // the element with id="SomeElementId" to whatever the new content is
        $objResponse->assign("lnkFav","innerHTML", 'xajax response!');
 
        //return the xajaxResponse object
        return $objResponse;
    }
 
 
 
    function poi($id)
    {
        $this->load->model('poi');
        $this->load->model('picture');
        $this->load->model('comment');
 
        $data = array('xajax' => $this->xajax,
        					   'poi' => $this->poi->getPoi($id),
						 'pictures' => $this->picture->getPicturesForPoi($id),
        				 'comments' => $this->comment->getCommentsForPoi($id));
 
        $this->load->view('poiDetail', $data);
    }

Let’s break that down. The important steps are:

  • We initialize xajax in the constructor of the controller, and assign the xajax object to a class variable which we’ll pass to our view later
  • The php function we want to call via ajax is located in our controller (in this case “addFavorite”
  • The $xajax class variable which was initialized by our constructor is passed to our view to be used by the view. (the first array assignment in $data in the poi function–those other things like comments and pictures you probably won’t be using on your site. :) )

Add XAJAX to the View

In my case the view I’m loading in the poi function is poiDetails.php at /system/application/views/poiDetails.php. Here’s the pertinent code from the view:

<?php
require_once(APPPATH . "util/constants.php");
   // the sneaky bit.. tell xajax where to look for it's javascript files (web-accessible of course)
  $xajax->configure('javascript URI', base_url() . XAJAX_FOLDER );
  // this is the name of your controller. my controller was class View in view.php
  // so i have 'view' here.  what is your controller named?
  // this is another very sneaky bit.  we don't let it decide its own URI because
  // that only works if you are coming from the index() function in your
  // controller!!
  $xajax->setRequestURI(site_url('view'));
  // now print what we just configured
  $xajax->printJavascript();
?>
<!-- and finally a link to click on -->
<div id=lnkFav><a href='#' onclick="xajax_addFavorite();return false;">Add to Favorites</a></div>

Don’t forget the return false; after your xajax call and the # sign for the href value or your browser will take you to another page or jump to the top of the current page.

That’s it! There were a couple of sneaky things in there that took me forever to figure out, but hopefully I’ve saved you some measure of the pain I know. Now that I’ve just saved you 6 hours trying to figure that out, how about taking 5 minutes to help me with www.poipedia.org by adding a couple of points of interest? Thank you for your time.

iPhone SDK – How to determine if an NSString is numeric

October 10th, 2009

I was working with the iPhone SDK and needed to determine if an NSString was numeric. After a lot of searching I came up with this function that doesn’t rely on any third party libraries. It uses the numberFromString function from the built-in NSNumberFormatter. Feel free to use it in your applications. :)

/*
    Returns whether or not an NSString represents a numeric value.  
    For more info see:  http://appliedsoftwaredesign.com/blog/iphone-sdk-nsstring-numeric/
*/
-(bool) isNumeric:(NSString*) checkText
{
 
	NSNumberFormatter* numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
 
	NSNumber* number = [numberFormatter numberFromString:checkText];
 
	if (number != nil) {
		NSLog(@"%@ is numeric", checkText);
		return true;
	}
 
	NSLog(@"%@ is not numeric", checkText);
        return false;
}

You can invoke it like:

[self isNumeric:@"2"];
[self isNumeric:@"2.0"];
[self isNumeric:@"4"];
[self isNumeric:@"-1"];
[self isNumeric:@"asdf"];

and it will return output like:

2009-10-09 10:27:03.656 App[16351:207] 2 is numeric
2009-10-09 10:27:03.658 App[16351:207] 2.0 is numeric
2009-10-09 10:27:03.659 App[16351:207] 4 is numeric
2009-10-09 10:27:03.659 App[16351:207] -1 is numeric
2009-10-09 10:27:03.660 App[16351:207] asdf is not numeric

Don’t forget to declare the prototype in your .h file:

-(bool) isNumeric:(NSString*) checkText;

Enjoy!

Spoons 1.1 Submitted

February 23rd, 2009

Thank you to everyone who purchased Spoons! We’re really humbled you like our app. With that, we’re happy to let you know Spoons 1.1 has been submitted to iTunes!

The new features we’ve added in version 1.1 are:

  • New Latin background track
  • New electric guitar background track
  • New electronic background track
  • New wooden spoon type (in additional to the default metal spoons)
  • Improved audio compression for lower memory footprint
  • Minor UI enhancement on the help screen

We would love to know what you want to see in the next version. Post in our forum and let us know.

Thank you for playing Spoons!

Spoons 1.1 In the Works

February 18th, 2009

We’re hard at work on our next update to Spoons. Coming in the next release:

  • Two new background tracks
  • Improved sound compression for smaller memory footprint

We’re also planning on adding another spoon-type (wooden spoons!), but if it doesn’t make it into 1.1, we’ll have it in 1.2 for sure. :)

The hardest part? Finding good background music! What type of music do you want to play the spoons to? Spoons aren’t just for Blues right? ;)

Let us know what you think over in our forum, and thanks so much for playing Spoons!

Spoons 1.0 Released

February 16th, 2009

Spoons is now available in iTunes! Click here to be taken to the iTunes product page.

We are happy to be the first Spoons app to be released to iTunes. :)

We are looking forward to adding new background tracks in the next release. We like to roll out releases frequently with fewer features in each release rather than a big release months and months away. This way, we can get rapid feedback from our users and better tailor the software to their liking.

Thanks for all your support!

Rounding a number

January 10th, 2009

This is an oldie but goodie. One of the first programming problems students run into is “How do I round a number?”  I had this question once too, and here’s the answer:

1.)  Add 0.5 to the number

2.)  Typecast to an integer.

In code this looks like:

double x = 12345.6789
int y = (int) (x + 0.5);

Hope this helps!