mcottondesign

Loving Open-Souce One Anonymous Function at a Time.

Making a 3rd-party JavaScript widget

At QliqUp, we had the idea of making a widget that merchants could place into their existing webpage that would let them show the current deals they offer. This was mostly straight forward but I wanted to explain some of the sharp edges that slowed us down.

You can see the final product at: http://qliqup.com/widgets/

First we had to make a public endpoint inside of our API. I left out some the docstrings because it only cluttered this example.

class PublicDealsHandler(BaseHandler):
    def read(self, request, response, id=''):

        if not id or id is '':
            return response.send(errors="Please specify a valid business", status=404)

        ret = []

        deals = Deal.objects.filter(business=id)
        for d in deals:
            ret.append({'name':d.business.name, 'data':d })

        response.set(deals=ret)
        return response.send()

This outputs JSON that looks like this (shortened down for this blog post):

{
    "errors": [],
    "data": {
        "deals": [
            {
                "data": {
                    "qpoint_cost": 250,
                    "description": "Receive a free Appetizer from Sam's Burger Joint. ",
                    "never_expires": true,
                    "redeemed": 0,
                    "text": "Free Appetizer From Sam's Burger Joint!",
                    "expires": null,
                    "unlimited": false,
                    "limit": 100,
                    "purchased": 0,
                    "additional_details": "Free Appetizer From Sam's Burger Joint!",
                    "id": 104
                },
                "name": "Sam's Burger Joint"
            }
        ],
        "messages": []
    },
    "success": true
}

Now on the client side we need make a single script they could include. We also had to wrap it up in a closure to keep things nice

(function($) {

    var ss = document.createElement("link");
    ss.type = "text/css";
    ss.rel = "stylesheet";
    ss.href = "http://static.qliqup.com/qliq_deals/style.css";
    document.getElementsByTagName("head")[0].appendChild(ss);

    // regular jQuery goes here

})(jQuery)

And now you can include it with something like this:

<script type="text/javascript" src="http://static.qliqup.com/qliq_deals/script.js"></script>