Blogs

Introducing the SPA JQuery Library

by User Not Found | Feb 23, 2012

Download the Source HTML Page - testpagejquery.zip 

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 http://lorempixel.com.

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="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://www.fujifilmapi.com/docs/spajs/spajquery.js"></script>
     
<script type="text/javascript">
    //Code from post goes here
</script>


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("https://preview.webservices.fujifilmesys.com/spa/v2/", "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 lorempixel.com, 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);
    lineItem.AddUpdatePage(page);
    //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", "http://lorempixel.com/1024/768", "1024,768,0,0,1024,768,0,0", null);
    page.AddUpdateAsset(asset);
 
    //add billTo using the AddBillTo method
    spa.AddBillTo("Jeff", "Bloom", "5852592897", "jbloom@fujifilm.com", 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", "jeffbvox@gmail.com", 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})
    }
    else
        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 - testpagejquery.zip

25 Comments

  1. 1 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.
  2. 2 Martin Jam 19 Apr
    This library can lead Hire Research Paper Writers-AssignmentKeen.com 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.
  3. 3 Peter Kevin 19 Apr
    You can see the Quality Homework at Assignmentland.com 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.
  4. 4 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.
  5. 5 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?
  6. 6 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.
  7. 7 results.itschool.gov.in 03 Apr
    Kerala SSLC/10th Class Exams 2017 held by the Kerala Board Of Secondary Education in the month of March 2017. get results.itschool.gov.in kerala sslc 2017
    results.itschool.gov.in
  8. 8 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.
  9. 9 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.
  10. 10 jio cabs app download 09 Mar
    i like this post and website
  11. 11 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 http://www.paperomatic.com/term-papers/ to get help from assistant.
  12. 12 super bowl 2017 live 28 Jan
    http://www.superbowl2017stream.com/
  13. 13 xbox live 21 Jan
    Hellow guys you can crack xbox console for the  free xbox live codes online.
  14. 14 rscit training 20 Jan
    Introducing the SPA JQuery Library thanks for share me the info.
  15. 15 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 Buyassignmentservice.com get a best guidelines and proposition to create your papers.
  16. 16 Super Bowl 2017 11 Jan
     Catch every moment of the Super Bowl 2017 live on 2 Giant screen projectors.
  17. 17 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.
  18. 18 192.168.1.1 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.

  19. 19 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

  20. 20 jobspoint 12 Dec
    I like this site and article as well. 
  21. 21 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.
  22. 22 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 
  23. 23 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.
  24. 24 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="http://www.clazwork.com">best essay writing service</a> to get a best guidelines and suggestion to write your essays.
  25. 25 Will Laurance 22 Oct
    Hey!

    Is this library open source anywhere?

    Thanks,

    Will

Comment

  1.