Contact Me


Recent Posts


Categories


Archives


Tags

3d actionscript Actionscript 2 Actionscript 3 api APIs as2 as3 brand caching carousel channel code compress contest contract CSS Flash flv fp10 free freelance gadget gadgets gdata google JavaScript jquery mvc papervision papervision3d PHP player playlist puremvc pv3d search tube tutorial twitter video widget XML you youtube

Recent Comments

  • Ahmed: Can you put up an example?
  • Ahmed: Hmmm sorry this is a tough one but I don’t work with ASP.NET! Sorry!
  • Michael: Good example but one question… in all the slider skinning I see with Flex the thumb overruns the left...
  • venkata: Hi I am using OAuth to connect to youtube api. I got accessToken and TokenSecret for a particular user. Now...
  • Ahmed: Good old flexlib, what component are you using?

Links


Help end world hunger

jQuery’s Missing AJAX Function (and CodeIgnitor)

This is a really handy tip if you use jQuery frequently and are receiving JSON data back. jQuery’s “$.post” allows you to do a POST call to your application and get the data back, but you have to flag the type of data being received by jQuery so that it can parse it.

This seems silly as jQuery’s strap line is “write less, do more”. So instead of having to do this all the time you want to receive and parse JSON:

1
$.post( url, [ data ], [ callback ], 'json' );

It’s much better to define a new function called “$.postJSON” like so:

1
2
3
4
$.postJSON = function(url, data, callback)
{
    $.post( url, data, callback, 'json' );
};

Now this is listed on the jQuery web site, but it just makes me wonder why it’s not put into the code base permanently. It’s a bit of a shame, but the code can be optimised. For example, when I was working on a project that was built on CodeIgnitor, I modified the function so that I didn’t need to specify the URL as I always used the same controller for my AJAX calls and sent a POST variable called “method” to handle the routing of the call. I had this basically:

1
2
3
4
5
6
var ajaxURL = '/path/to/ajax_controller';

$.postJSON = function(data, callback)
{
    $.post( ajaxURL, data, callback, 'json' );
};

And then within CodeIgnitor I had my controller launch a library that had a simple switch that routed the calls, like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Backend_lib
{
    function route($method,&$output)
    {
        $CI =& get_instance();     
       
        switch ($method)
        {
            // Login
            case 'login_user':
            $CI->load->library('auth_lib');
           
            $output = $CI->auth_lib->login_user();
           
            break;
        }
    }
}

This keeps the JavaScript and PHP code nice and simple and easy to maintain.


Leave a Reply

Your comment:

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Fork me on GitHub