funkatron

First Steps with CodeIgniter and JQuery

When it came time to start adding some required AJAX functionality to WapSnap, I knew that hunting down and learning an AJAX/Javascript framework was going to be one of my most daunting tasks. I had played with YUI in the past with little success, likely due to my limited Javascript experience. After speaking with a few friends that are javascript experts I decided to start with JQuery.

To start with all I needed was callback functionality. Since the only tutorial on the JQuery tutorials page with callback in the title was AJAX Callbacks with JQuery, naturally that is where I started. In this tutorial there is a get method that looks like this:

  1. $.get(“giveMeSomething.php”, { number1: number1, number2: number2 },
  2. function(data){
  3. alert(“Data Loaded: “ + data);

The problem with the way this is written is that like the page the tutorial is hosted on, it generates ugly URLs.

WapSnap is built on the CodeIgniter framework which in the default installation means that you do not use hideously formatted parameters in the URL such as ?id=1&type=2. In CI ( CodeIgniter ) the example just given could look like /1/2 or /id/1/type/2. This structure which I find more enjoyble and visually appealing became my first problem with the mentioned article.

The code snippet shown automatically adds a question mark after the GET url and then formats and appends the data in the second parameter. This instantly caused a problem which lead me to a good bit of searching. After Google didn’t return enough entry level help for my searches I turned to the JQuery IRC channel which resulted in a solution.

For anyone else that may be looking for a solution to searches like “remove ? from get request in JQuery” or “remove question mark from get request in JQuery” The solution for me was to append the variable in the first parameter and leave out the second parameter. Which resulted in the following:

var db_id = $(‘#db_server’).attr(‘value’);

$.get(“ajax/getdatabases/” + db_id, function(data)
{

Now that the URL was being requested correctly I needed to parse the data returned. More searching lead to a funkatron article: Safely Parsing JSON In Javascript. For those of you who don’t know Funkatron, he is a well know PHP speaker, creator of Spaz the open source Twitter client, and a hilarious and helpful guy. He actually gave me my first CodeIgniter lesson on the floor at PHP | Works 08. With this article I was able to quickly and easily parse the JSON data sent back from my PHP page, something that wasn’t so easy when I first tried YUI a few months ago.

While I was debugging with Firebug I noticed that as a Javascript noob the errors weren’t as helpful as they could have been so I searched for a Javascript syntax checker. I immediately found JSLint which gave a little more in depth errors.

Tags: , , , ,

Wednesday, March 4th, 2009 Development, WapSnap Comments