View all of fi_labs' updates Kontained: 3 months ago

Custom AJAX Wrapper for jQuery

description of image

 

We write a lot of our Javascript with the help of jQuery. 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 my custom AJAX wrapper for jQuery.

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

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

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

I will base the example loosely on a CRUD schema.

Example:

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

            // Execute some global method here

            // Execute user defined method
            if (typeof payload.beforeSend === 'function'){
                payload.beforeSend();
            }
        },
        
        // Global success wrapper with user defined function
        success: function (data) {

            // Execute some global method here

            // Execute user defined method
            if (typeof payload.success === 'function') {
                payload.success(data);
            }
        }
    });
};

Now that we have set up our basic framework, we 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 = {

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

        // 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. Please ask any questions or leave comments below!

Karl Stanton - Developer @ Fi Stockholm

 

Share this entry

Close
Invalid e-mail format, please try again

Your friends will be notified via email about this entry.

Remove Email

You are about to remove the selected emails from your list. Are you sure you want to remove them?

Yes
Cancel
Select All Deselect All Remove Selected

Share with third party communities This will take you to a new window.


Report Inappropriate Content

Close
Details
Operations

Thank You!

The safety and legitimacy of Kontain's content is paramount to us. We will be investigating this content shortly. Here is what you reported:

Report Category Harmful of Dangerous Acts Report Detail Drug Abuse
Additional Information

Lorem ipsum dolor sit amet consectetuer adipiscing elit penubrum purous

Comments (9)

  • Paul 3 months ago

    Great stuff. I often add in a timestamp to wrappers (which are returned as part of the script's response) so that if there are a lot of requests in quick succession you can compare the timestamp of the response to the most recently dispatched request. That's saved my bacon a good number of times.

     

    I am a big fan of this kind of centralization and wrapping - keeps thing very neat and easy to test / debug :]

     

  • Author
    fi_labs 3 months ago

    For sure! It's also often best to suffix the endpoint with a timestamp to help break cached responses. I hope people can take this as the base and extend upon it for their own applications!

     

    Thanks for your comment, Paul!

  • decembersoul 3 months ago

    Nice one Karl!  Makes it so easy to add global handles for exceptions and hook in functionality like re-login and re-execute last action if the session has expired. 

  • Tekkaman S... 3 months ago

    So much brain power in this post.

     

  • Everardo 3 months ago

    Great article. How can I add the beforeSend callback like in this example:

    $.ajax({
        url: url,
        beforeSend: function(xhr) {
             xhr.setRequestHeader("SOAPAction",'http://mycompany.org/myservice/WebService.GetOrder');
        },
        type: "POST",
        dataType: "xml",
        data: soapMessage,
        complete: endSaveProduct,
        contentType: "text/xml; charset=utf-8"

        });

    Thanks,

    Everardo

     

  • Sebastian 2 months ago

    Very nice object. however You can optimize the code.

    /**
     * Outline our webservices
     * @param {String} action - AJAX action to perform
     * @param {Object} payload - Javascript object containing AJAX method properties
     */
    Website.Webservice = function (action, payload) {
           var setAction = (action === "read")?"get":action
            payload.type = (setAction !== "get")?'POST':'GET';
            payload.url = '/ajax/' + setAction + '_data.php';
        // Call the global AJAX method
        Website.AJAX(payload);

    };

     

  • karlstanton 2 months ago

    Quoted from: Everardo - "Great article. How can I add the beforeSend callback like in this example:

    $.ajax({
        url: url,
        beforeSend: function(xhr) {
             xhr.setRequestHeader("SOAPAction",'http://mycompany.org/myservice/WebService.GetOrder');
        },
        type: "POST",
        dataType: "xml",
        data: soapMessage,
        complete: endSaveProduct,
        contentType: "text/xml; charset=utf-8"

        });

    Thanks,

    Everardo

     "

     

    It would be added in the updateUserData function. Notice how the object replicates the AJAX object.

  • karlstanton 2 months ago

    Quoted from: Sebastian - "Very nice object. however You can optimize the code.

    /**
     * Outline our webservices
     * @param {String} action - AJAX action to perform
     * @param {Object} payload - Javascript object containing AJAX method properties
     */
    Website.Webservice = function (action, payload) {
           var setAction = (action === "read")?"get":action
            payload.type = (setAction !== "get")?'POST':'GET';
            payload.url = '/ajax/' + setAction + '_data.php';
        // Call the global AJAX method
        Website.AJAX(payload);

    };

     "

     

    We do optimize our code for production, however this article is deliberately verbose for the purpose of easy reading. Thanks for your comment!

  • Alan Smith 2 months ago

    Great article!

What do you think?

Collapse

Friends / Following

Loading…
  1. karlstanton

    Karl Stanton


    51 Updates Updated: 37 hours ago
  2. Johnny

    Johnny Michaelsen


    141 Updates Updated: 3 days ago
  3. Fi

    Fi


    171 Updates Updated: 4 days ago
  4. hakim

    Hakim Elhattab


    9 Updates Updated: 4 months ago
Collapse

More from fi_labs

Subscribe to fi_labs

Feeds are an easy way to stay up-to-date with websites you love. Feeds automatically update and show you the newest content without you having to check. Read more here.

All you need is a Feed Reader, like these free ones for Mac and PC.

Close
Collapse

Featured Kontainers

Copyright © 2010 Kontain LLC. All rights reserved