Introducing the SPA JQuery Library

by User Not Found | Feb 23, 2012

Download the Source HTML Page - 

If you're using JQuery to call AJAX methods and to perform DOM manipulations, have we got a library for you!  To make things super simple for integrating with our Smart Publish API (SPA), we've developed a small javascript library that encapsulates the classes and methods for interacting with the SPA services. In this article, I'll walk you through using the api to order a random product from our catalog using an image served up by

Let's start with a sequence diagram that details the interactions of a content creation application (Client) and the SPA JQuery Lib (SPA Lib).  

Client to SPA Library Sequence

In this sequence, after the content is created by the app, it initializes the library by instantiating a SPA object.  This object orchestrates building up the order and communicating with the SPA services. The sequence then details how the order is populated with an item and image, how the billing and shipping information is set, how the order is submitted, and then finalized through the CheckOut call.  This sequence is just an example of the flow of calls into the library.  If it doesn't work for your app, feel free to deviate from it to suit your needs.

Now that we have a sequence of calls to be made, let's go through some code to make it happen.  We'll have a very simple web page that only displays a running log of the interactions with the SPA library. We'll use JQuery to append messages to a span so we can see where we're at in the flow.  The javascript that instantiates the spa object and starts things off will be executed from the JQuery $(document).ready function. 

To begin with, you'll need to reference the JQuery library, either from a local copy or through a CDN version (as shown below), and  the SPA JS library. If you're writing a self contained web app, you can download the file from the linked location to have a local copy, but we recommend referencing it from our services in case we need to make a bug fix (we promise not to change the interfaces though).  We'll also place all of our other logic within a script tag in the head. From this point forward, the code detailed in this post is inside of this tag. 

So far, we've added this to the head area of the html page:

<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript">
    //Code from post goes here

We're now ready to use the SPA javascript classes.  The library contains a main class called SPA (genius, right?) that is used for encapsulating an order, product catalog, and RESTful service configuration properties.  There are data classes as well, that represent the components of the order that you can new up and add to the order. Some of these classes contain helper methods to perform operations on them.

The SPA constructor takes in the Root URL to the services and the API Key that is generated in our Partner Workspace Applications page (you need to be signed up to see this page).  The API Key uniquely identifies your application and is used to tie orders back to your company.  This ensures that you get paid for the orders placed through your application, so make sure you create your own!  We'll be using a test API Key for the code samples in this post.Since we're going to start processing when the page loads, we'll use the document ready JQuery method to create a spa object and go get the catalog.  Here's what it looks like:

//scoping spa at the global level so that we can access it in other functions
var spa = null;
$(document).ready(function () {
    //instantiate SPA with the rest root URI and the APIKey (REMEMBER TO CHANGE THE API KEY TO YOUR OWN)
    spa = new SPA("", "01dfd4d6da14491ebbf9745d7c9e0891");
    //get the catalog so we know what's available and their prices
    $("#status").text("Getting Catalog");
    spa.GetCatalog({ Success: PlaceOrder, Error: ErrorFunc });   
function PlaceOrder(msg) {
    //We'll talk about this next
function ErrorFunc(response, textStatus, errorThrown) {
    $("#status").append("<br/>Error while calling service. status = " + textStatus + " errorThrown = " + errorThrown);
    if (response.responseText)
        $("#status").append("<br/>   response.responseText = " + response.responseText);

A couple of things of interest in the above code block: spa is declared outside of any function so it is global in scope (very helpful since we're doing asynchronous actions), and the spa.GetCatalog call takes in an object with properties of Success and Error as all of our asynchronous methods do. The values of these properties are functions to call upon Success and Error. Both of these methods should accept parameters similar to the JQuery $.ajax success and error properties.  If an error occurs on the service side due to business logic or validation rule violation, the response.responseText property will contain a status json string that defines the error code and error description that will tell you what the problem was.  If we're successful in getting the catalog, we're now ready to start populating the order that was created when we instantiated the spa object.

The PlaceOrder function selects a random item from the catalog adds it to the order with an image provided by, a great site if you're looking for placeholder images.

function PlaceOrder(msg) {
    $("#status").append("<br/>Catalog Retrieved");
    //Normally we would now present the catalog to the customer for product selection,
    //but for the demo's sake, we'll randomly pick an item and order it.
    var from = 0;
    var to = spa.Catalog.Products.length - 1;
    var itemIndex = Math.floor(Math.random() * (to - from + 1) + from);
    var catalogItem = spa.Catalog.Products[itemIndex];
    $("#status").append("<br/>Ordering " + catalogItem.Name);
    //add a line for the catalog item and a quantity
    var lineItem = spa.AddLineItem(catalogItem, 1);
    //add page 1 to the line item;
    var page = new SPAPage(1);
    //add asset to the page. The fourth parameter to the SPAAsset constructor is the crop string.  It is a comma separated list
    //  of numeric values that define the reference height and width, the inner coordinates of the area to place on the product,
    //  the rotation to apply to the cropped image, and a bit indicating whether to flip the image. The format is
    //  below (ommiting the brackets)
    //       [the width of original image], [height of original image], [left x coordinate], [top y corrdinate], 
    //       [right x coordinate], [bottom y coordinate], [angle], [flip 1=yes 0=no]
    var asset = new SPAAsset(1, "Jeff's FB Profile Pic", "", "1024,768,0,0,1024,768,0,0", null);
    //add billTo using the AddBillTo method
    spa.AddBillTo("Jeff", "Bloom", "5852592897", "", null, "155 Bellwood Dr.", null, "Rochester", "NY", "14626", "US");
    //add shipTo using alternative method. There is a spa.AddShipTo method if you want to use it.
    var shipAddress = new SPAAddress("418 Mudvail Lane", null, "Rochester", "NY", "14626", "US");
    var shipToPerson = new SPAPerson("Jeff", "Bloom", "5555555555", "", null, shipAddress);
    spa.Order.ShipTo = shipToPerson;
    $("#status").append("<br/>Submitting Order");
    //submit the order
    spa.SubmitOrder({ Success: OrderSuccess, Error: ErrorFunc });   

I've tried to comment the code as much as possible, so hopefully you get the gist of what's going on there.  The few things to note is that after spa.SubmitOrder is called each of the line items in the Lines array now contains a property called LinePreviewThumbnail. The value is a URL to an image that is a composite of the asset and the product which can be used to represent the product being ordered to the customer.  spa.OrderTotal is also populated which contains properties for TotalItemPrice, TotalTax, TotalShipping, and TotalPrice (the sum of the other three).

At this point, we've built up an order and submitted it to the SPA services. We can display product graphics with the customer images applied, and can display how much it's going to cost to produce the order.  The only thing left now is to perform a checkout by sending up the payment information to the service.  Since all of our services require HTTPS, this will be a secure transaction.

function OrderSuccess(msg) {
    //make sure we have totals
    if (spa.OrderTotal.TotalPrice) {
        $("#status").append("<br/>Order Submitted. OrderId = " + spa.OrderId + " Order Total = " + spa.OrderTotal.TotalPrice);
        //checkout here
        $("#status").append("<br/>Calling Checkout");
        spa.CheckOut("5328241721194789", "11", "2012", "123", {Success: CheckoutSuccess, Error: ErrorFunc})
        alert("no totals! :(");
function CheckoutSuccess(msg) {
    $("#status").append("<br/>Checkout Success! Order is complete. OrderID = " + spa.OrderId + " ETA = " + spa.ETA);

After the CheckOut method is called, the spa.ETA property is populated with the expected delivery time for the order. With that, we're done!  The order has been placed and it's on it's way to be fulfilled and delivered to your customer, and you also have some money coming your way based on the profit margins you set in your product catalog (you need to be signed up to see this page). 

Download the Source HTML Page -


  1. 1 Abby 26 May
    You made some nice points there. I will bookmark your blog
  2. 2 PhD Thesis Writing Services 25 May

    I am a regular reader of your blog. the blog is very interesting and will be much useful for us. i really enjoyed very much with this article here. Really its a amazing article that i had ever read.
  3. 3 titanium backup free download 23 May
    titanium backup free download  is the best app for backing up your devices. There is always a risk of losing important information while using a cellphone
  4. 4 Case Study Assignment Help 22 May

    Thats Good to be hearing here Thanks For More Helpful Tips.

    href="">Case Study
    Assignment Help</a>
  5. 5 Kelvin Micheal 12 May
    We all students need this type of stuffs because we need to mention something amazing because of doing something unique in our life to become supportive ways Dissertation Writing Service some students needs.
  6. 6 12 May
    I have tried and tested it, however I am unable to do it after once, no idea wht went wrong but I am still trying and trying again to achieve my desired targets.
  7. 7 mobdro ipad 06 May
    mobdro ipad is the best app to watch various shows and videos for free with the help of the mobdro for iPad and ios
  8. 8 04 May
    The Maharashtra State Board of Secondary & Higher Secondary Education is making all preparations to declare Maharashtra SSC Result 2017
  9. 9 Custom Essay Writing 03 May
    It's simple and familar with jQuery users. Even you can use jQuery code in this framework.Most front-end developers are familar with jQuery, but jQuery doesn't support architecture. Just make things possible, getting messed often. To solve this problem, some people suggest huge and new framemworks and libraries such as AngularJS, Amber, React. But learning these heavies are very tough. I suggest SPA jQuery.
  10. 10 FDGSDF 27 Apr
  11. 11 h b 25 Apr

    First, I have a
    confession to make. I am very bad with managing my time. I have always had
    loads of stuffs to do, all piled-up until the very last minute.
    term paper writing service
  12. 12 Bradley Willis 24 Apr
    Such a useful information you have shared through out this article as so many learners are getting their assistance through online platforms,so this one will be quite useful for getting an instant assistance regarding web development and they can also get many useful instruction for their career orientation in their respective field and i must say that online ways is the best way to get an assistance for any purpose,as i have seen many individuals those buy dissertation online for their academic writing help and it is quite reliable thing for them as they can go through with for saving their time and effort.And you will always get a best result through out online platforms.Thanks for sharing it.
  13. 13 Add Addy 22 Apr
    In wealth of semi of the student enunciation to the NRI Matrimonials in United Kingdom encompass a measure of correspondence with their compartment telephone all through social event case for all division.
  14. 14 Martin Jam 19 Apr
    This library can lead Hire Research Paper valuable stuff to control new innovations that super intriguing things created with the arbitrary item. Share these sorts of articles to my companions who get a kick out of the chance to peruse the sites for expanding extraordinary considerations and data.
  15. 15 Peter Kevin 19 Apr
    You can see the Quality Homework at film designer gave organize entrance on spring refreshes. This library can lead some helpful stuff to control new creations that super fascinating things created with an irregular item. These are all getting find new subjects and surveys for us.
  16. 16 Earl Anderson 19 Apr
    If I understand correctly and you're concerned about (what essentially amounts too) conflicts with the CSS, then including your own custom stylesheets after the library ones is the best starting point; as @rthor has pointed out.
    However this may not solve every issue, purely because it also depends on the specificity of the CSS selectors. There's a good article here on CSS specificity - which should also enable you to effectively combat any CSS conflicts that arise.
    Now scope? That's a different subject, and one that's a little more confusing - purely because of (surprise surprise) browser implementations differ. You can just a polyfill for older browsers but that's not great. It's purely a HTML5 feature it seems Unless you're talking about the :scope psuedo-selector.. which is working draft for CSS Selectors  Kids Activities
    I'm sure some front-end wiz will be able to give you low down specifically regarding scope, as I expect my solution leaves a little bit to be desired. You could always make use of container elements (gasp.. I know, not ideal.) and ensure all styles specifically target children of the a container element.
  17. 17 Earl Anderson 19 Apr
    I am building a single-page application (SPA) based on jqWidgets library (it is in turn built on the top of jQuery UI).
    Now I would like to use a widget-component available built on another framework (possibilities are Ext JS or jQuery UI). 
    Biology Research Paper
    I'm concerned about the possible problems with CSS compatibility; I read a lot on the topic and found about so called CSS Scope attribute. Unfortunately, I don't see any recent text on the subject, so I am not sure about its state.
    Are there any other possibilities to battle this problem in a SPA? Or Workarounds?
  18. 18 Johnie Hickman 05 Apr
    since you won't have many customers to do my dissertation doing this at one time, you don't need a database. only a little apache security.
  19. 19 03 Apr
    Kerala SSLC/10th Class Exams 2017 held by the Kerala Board Of Secondary Education in the month of March 2017. get kerala sslc 2017
  20. 20 Kamanti Wosterd 24 Mar
    Is SPA Jquery library part of min js? I am an essay agents writer so I don't know much of the code. I work at give me answers for my homework online for students.
  21. 21 Micheal 15 Mar
    Everyone wants a magic, which can do their work, if you are having problem with your coursework writing, then get best coursework writing service by excellent academic help.
  22. 22 jio cabs app download 09 Mar
    i like this post and website
  23. 23 William F. Richardson 08 Mar
    This library can lead some useful stuff to manipulate new inventions that super interesting things developed with random product. There are many students who can take help from to get help from assistant.
  24. 24 super bowl 2017 live 28 Jan
  25. 25 xbox live 21 Jan
    Hellow guys you can crack xbox console for the  free xbox live codes online.
  26. 26 rscit training 20 Jan
    Introducing the SPA JQuery Library thanks for share me the info.
  27. 27 John Martin 16 Jan
    I get a kick out of the chance to share these sorts of articles to my allies who seize the opportunity to examine the destinations for growing inconceivable thought and information. You can insinuate best article making organization to get a best guidelines and proposition to create your papers.
  28. 28 Super Bowl 2017 11 Jan
     Catch every moment of the Super Bowl 2017 live on 2 Giant screen projectors.
  29. 29 Master’s Thesis Consulting Pricing 06 Jan
    A wealth of gratitude to you. I get a kick out of the opportunity to share these sorts of articles to my companions who jump at the chance to peruse the sites for expanding incredible examinations and data. You can see the film Master’s Thesis Consulting Pricing engineer gave organize gateway on spring overhauls. JQuery intends to encourage each one of these issues by giving a lightweight library that incorporates many advanced and cross-program abilities to the standard vernacular.
  30. 30 Router Configuration 06 Jan
    192.168.l.l IP Address  is a numeric value assigned to every computer, Router, Printer and other devices which are required for the purpose of network communication.

  31. 31 osmania university results 2017 22 Dec
    Junior & Senior Diploma in German & French November, 2016 results ... of UG (CBCS) Semester-I Inernal Marks for the academic year 2016-2017
    osmania university results 2017

  32. 32 jobspoint 12 Dec
    I like this site and article as well. 
  33. 33 Jack kevin 03 Dec
    JQuery means to facilitate every one of need an essay written these issues by giving a lightweight library that includes many progressed and cross-program capacities to the standard dialect.
  34. 34 Adam Micheal 25 Nov
    We have to read all the things in our life like this blog but we still doing such things in proper way of doing such amazing things in life expert research proposal writers 
  35. 35 JohnE 01 Nov
    You can see the film developer provided network portal on spring updates. That everything is needed to understood the research paper writing services website given new corporate reviews. These are all getting find new topics and reviews for us.
  36. 36 Randalltbartel 31 Oct
    An abundance of thanks to you. I get a kick out of the chance to share these sorts of articles to my friends who like to read the websites for increasing great contemplations and information. You can refer <a href="">best essay writing service</a> to get a best guidelines and suggestion to write your essays.
  37. 37 Will Laurance 22 Oct

    Is this library open source anywhere?