Karl New York City, United States of America.

English American

Posts Tagged ‘jQuery’

Custom AJAX Wrapper for jQuery

Friday, October 16th, 2009

I write a lot of my Javascript with the help of jQuery, and one of it’s finest features is it’s extensibility and powerful internal functions. For larger sites, especially portals, AJAX can become messy if it’s not controlled, and when things get out of hand, it’s often hard to trawl through your scripts to make changes.

That’s one of the reasons why I wrote (and use almost daily) my custom AJAX wrapper for jQuery.

The idea.
Centralize one $.ajax() method, and have methods external to jQuery control the data and callback methods before firing.

This allows for a global wrapper on all before and callback methods in case you need to do things like: show loading animations, run site statistics, setup error handling, etc.

The code.
I like to use namespaces in my projects, so I will be giving you a basic outline of a namespace setup, and then how an external function can interact with the global AJAX method.

I will base the example loosely on a CRUD schema.

// Create our namespace
var Website = {};

/**
 * Outline our webservices
 * @param {String} action - AJAX action to perform
 * @param {Object} payload - Javascript object containing AJAX method properties
 */
Website.Webservice = function (action, payload) {

    switch (action){

    case 'create':
        payload.type = 'POST';
        payload.url = '/ajax/create_data.php';
        break;

    case 'read':
        payload.type = 'GET';
        payload.url = '/ajax/get_data.php';
        break;

    case 'update':
        payload.type = 'POST';
        payload.url = '/ajax/update_data.php';
        break;

    case 'delete':
        payload.type = 'POST';
        payload.url = '/ajax/delete_data.php';
        break;
    }

    // Call the global AJAX method
    Website.AJAX(payload);

}

/**
 * Fires off the AJAX object with user defined payload information.
 * @param {Object} payload	- AJAX data options to bind to the jQuery object
 */
Website.WebService.AJAX = function (payload) {

    // If dataType wasn't specified in the payload, default to 'html'
    var dataType = (payload.dataType !== undefined) ? payload.dataType : 'html';

    // jQuery AJAX object
    $.ajax({

        // Normal properties
        type: payload.type,
        url: payload.url,
        data: payload.data,
        dataType: dataType,

        // Global beforeSend wrapper with user defined function
        beforeSend: function () {

            // Do global here
            if (typeof payload.beforeSend === 'function'){
                payload.beforeSend();
            }

        },

        // Global success wrapper with user defined function
        success: function (data) {

            // Do global here
            if (typeof payload.success === 'function') {
                payload.success(data);
            }

        }
    });

};

Now that I have set up our basic framework, I can fire off any AJAX request with minimal code, and abstract any intense data mining functions and other methods from our AJAX process. This allows for clean and controllable code.

/**
 * Some function or event that fires off AJAX
 * @param {Object} data - Javascript object containing user data
 */
var updateUserData = function (data) {

    // Create the AJAX property object
    var bundle = {

        data: {
            'user_id': data.user_id,
            'user_email': data.user_email,
            'user_firstname': data.user_firstname,
            'user_lastname': data.user_lastname
        },

        beforeSend: showSpinningLoader,

        // Success callback function
        success: onRefreshSuccess

    };

    // Fire the bundle off
    Website.WebService('update', bundle);

};

And there you have it. Simple and easy to use. Now you can trigger AJAX from anywhere in your application with all processes centralized.

My first week…

Friday, December 5th, 2008

So, it’s the end of my first week of work here in Stockholm. I’m sorry for the half-arsed posts, but I’ve been really busy, thus really tired.

I have hit the ground running. I am caught up in a new project for EA which is quite massive, and I’ve spent most of my time developing plug-ins for jQuery, which is really exciting for me as I do enjoy component work. Lots of little tiny projects that turn over quickly keep the days rolling fast and the hunger to develop strong.

My new team totally rock. A very (very) talented bunch of people who are experts in their respective fields, whether it be Flash Developer, Designer, Producer, HR, Office Manager, whatever, people are here because they love it, you can see it when you walk in.

One of the best things about working at F-I and I guess Stockholm in general is the no-shoes custom. It’s much like Japan (excluding restaurants and bars) where when you enter the office or home, you remove your shoes.  It certainly makes for a lot of sliding around hardwood floors and comfort when sitting on your ass all day. I guess the real reason is that you don’t drag snow and slush through the entire office or house.

I can dig it.

As for the picture on the right here. This is my work MSN list. If there was any better way to keep thinking about you-know-who (and who needs to be reminded really… miss you!), then this is it. :)

The weather has been dry these past few days, and hopefully it stays this way on the weekend so I can clock a few K’s on the pushie. I have a nice 20km round trip which gets the heart started, so I look forward to that.

I also will be joining a gym very soon as absolutely no exercise is getting done. It’s all work, eat, sleep, work, eat, sleep, and, in the dark! I need to start exercising or I’m going to blow up like a led zeppelin.

Now that I have my AU -> EU adapter, I can shoot lots of photos for you all. I promise to get a nice set down after the weekend is out.

Stay in touch.

x