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

210 comments

Leave a comment
  1. bilal khan | Nov 11, 2019
    A commitment of gratefulness is all together for all the exertion in sharing this surprising post and I truly to welcome it. Your dedication and dependable work has helped you to pass on astounding quality articles everything consideredhttps://www.seopublissoft.fr/
  2. ahmed | Nov 07, 2019
    I read this article. I think You put a lot of effort to make this article. I like your workAccountant for Self Employed
  3. Petronio | Nov 06, 2019
    status whatsapp Best Attitude Whatsapp Status, Best Attitude Quotes for Whatsapp & Facebook, Attitude style status, Attitude Status for boys and girls.

  4. ahmed | Nov 05, 2019
    A dedication of appreciation is all together for all the effort in sharing this astounding post and I really to invite it. Your commitment and reliable work has helped you to pass on astonishing quality articles all things consideredTax Advice
  5. unique gift websites | Nov 04, 2019
    These are some great tools that i definitely use for SEO work. This is a great list to use in the future.. unique gift websites
  6. jimm | Nov 03, 2019

    développement application web

    I ‘d mention that most of us visitors are really endowed to exist in a fabulous place with very many wonderful individuals with very helpful things.

  7. jimm | Nov 02, 2019

    creer site e commerce

    I regularly visit this site to check out the events and functions and sometimes for resources. However, it has been a while that you have shared some news about latest or upcoming events.

  8. bilal khan | Nov 01, 2019
    An obligation of appreciation is all together for all the effort in sharing this amazing post and I really to invite it. Your dedication and constant work has helped you to convey extraordinary quality articles thusly'site e commerce
  9. bilal khan | Oct 31, 2019
    A debt of gratitude is in order for all the exertion in sharing this splendid post and I truly to welcome it. Your commitment and diligent work has helped you to deliver great quality articles this waysellsy
  10. bilal khan | Oct 30, 2019
    I truly recognize on a very basic level examining the majority of your weblogs. Just expected to incite you that you have individuals like me who worth your work. Completely a heavenly post. Finishes off to you! The data that you have given is especially utilized.navigation privée
  11. bilal khan | Oct 30, 2019
    I truly recognize on a very basic level examining the majority of your weblogs. Just expected to incite you that you have individuals like me who worth your work. Completely a heavenly post. Finishes off to you! The data that you have given is especially utilized.navigation privée
  12. ahmed | Oct 30, 2019
    Hi folks this is a decent spot and great game simply visit more data here free robux 2019 is an online computer game is a best quality and most recent rendition.Self Assessment Tax Return Accountants
  13. jjmm | Oct 30, 2019

    creation d application

    Always so interesting to visit your site.What a great info, thank you for sharing. this will help me so much in my learning

  14. jay | Oct 29, 2019
    Pretty suitable put up. I have just stumbled upon your weblog and enjoyed studying your blog posts very lots. I'm searching out new posts to get morevaluable data. Big thanks for the beneficial info.   mailjet
  15. bilal khan | Oct 27, 2019
    I genuinely acknowledge fundamentally scrutinizing most of your weblogs. Simply expected to prompt you that you have people like me who worth your work. Absolutely a magnificent post. Tops off to you! The information that you have given is particularly used.Best Products Reviews
  16. ahmed | Oct 27, 2019
    Incredibly not too bad blog and articles. I am realy very happy to visit your blog. By and by I am found which I truly need. I check your blog customary and endeavor to take in something from your blog. Thankful to you and holding on for your new post.Self Assessment Tax Return East Grinsteadahmed
  17. bilal khan | Oct 26, 2019
    Unimaginably made article, if simply all bloggers offered a corresponding level of substance as you, the web would be a fabulously improved spot. Very character blowing post, Thank you for sharing this data.création application mobile
  18. ahmed | Oct 24, 2019
    This is extremely a pleasant and instructive, containing all data and furthermore greatly affects the new innovation. A debt of gratitude is in order for sharing itSelf Assessment Tax Return Accountants East Grinstead
  19. markce | Oct 23, 2019
    we cant think courtney cox as well as donald arquette are getting a divorce!they were with each other with regard to Eleven years!안전놀이터
  20. bilal khan | Oct 22, 2019
    Fantastically composed article, if just all bloggers offered a similar degree of substance as you, the web would be a greatly improved spot. Extremely incredible post, Thank you for sharing this information.agence digitale
  21. ahmed | Oct 21, 2019
    A debt of gratitude is in order for the pleasant blog. It was exceptionally valuable for me. I'm upbeat I discovered this blog.Self Assessment Tax Return Accountants near me
  22. bilal khan | Oct 20, 2019
    That is truly something that we consider a ton. At the point when we thought up our key course of action, the fundamental segment was people. Hopkins is mind blowing because of the overall public who work here and learn here, so it's critical to use to keep them fulfilled and locked in.agence de communication digitale
  23. mira singh | Oct 20, 2019
  24. iram ali | Oct 20, 2019
     fuji films is making mark again in the world best paying slot games keep it up
  25. bilal khan | Oct 17, 2019
    Such a good post you share with North American nation, i actually appreciate your work and content plan and that i have found here several knowledgeable info this web site excellent for my want.marche saint pierre
  26. james | Oct 17, 2019

    This is a shrewd blog. I would not joke about this. You have such a great amount of learning about this issue, thus much enthusiasm. 

    Nigeria news

  27. jay | Oct 17, 2019
    Hello !! you are my active client. you are amazing to purchasing products. I hope you will again purchase my product.iphone aux adapter 
  28. dssd | Oct 14, 2019
    This blog is so nice to me. I will keep on coming here again and again. Visit my link as well.. remembrance sunday parade
  29. bilal khan | Oct 13, 2019
    Hello what a dazzling post I have gone over and trust me I have been paying extraordinary personality to this comparative sort of post for late week and hardly continued running over this. Much thanks and will search for more postings from you.certification d'immatriculation ccsl
  30. ahmed | Oct 13, 2019
    I have perused your blog it is useful for me. I need to express profound gratitude to you. I have bookmark your site for future updates.Forest Row Accountants
  31. ahmed | Oct 12, 2019
    enchanting post, stay aware of this interesting work. It really regards comprehend that this subject is being checked in like way on this site so cheers for setting aside time to talk about this!Pistaches
  32. sdsd | Oct 11, 2019
    I can’t imagine focusing long enough to research; much less write this kind of article.  You’ve outdone yourself with this material.  This is great content. https://www.liberoreporter.it/2012/04/sport/superstars-series-qualifiche-di-imola-terzo-posto-per-thomas-biagi.html
  33. ahmed | Oct 11, 2019
    Much obliged to you since you have been happy to impart data to us. we will consistently welcome all you have done here on the grounds that I realize you are worried about our.Noix
  34. remembrance sunday poems | Oct 11, 2019
    A great content material as well as great layout. Your website deserves all of the positive feedback it’s been getting. I will be back soon for further quality contents. remembrance sunday poems 
  35. ahmed | Oct 09, 2019
    It is somewhat generally excellent, by and by look at the information with this handleAccountants Crawley
  36. saeed khatri2 | Oct 08, 2019
    A great content material as well as great layout. Your website deserves all of the positive feedback it’s been getting. I will be back soon for further quality contents. Buy website Traffic
  37. bilal khan | Oct 08, 2019
    This is an extraordinary article, Given such a lot of data in it, These sort of articles keeps the customers excitement for the site, and keep sharing more ... favorable circumstances.agence digitale paris
  38. feel unique discount code | Oct 07, 2019
    Very useful post. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. Really its great article. Keep it up. feel unique discount code
  39. ali khatri | Oct 06, 2019
    A great content material as well as great layout. Your website deserves all of the positive feedback it’s been getting. I will be back soon for further quality contents. where to buy strawberry diesel in uk 
  40. bilal khan | Oct 05, 2019
    Such an edifying site. A commitment of thankfulness is all together for sharing. Furniture is a thing that we when all is said in done need in our home or work environment. In the event that you contemplating acquiring new products, by then I propose you purchase victorian enhancements. Since it's inside and out satisfying and the game plan is so flawless.couteaux de poche
  41. 소액결제현금화 | Oct 05, 2019
    I admit, I have not been on this web page in a long time... however it was another joy to see It is such an important topic and ignored by so many, even professionals. professionals. I thank you to help making people more aware of possible issues. 소액결제현금화
  42. ahmed | Oct 04, 2019
    i love these types of artical i will come back again and now i bookmarked your site,, thanks for this contentCrawley Accountants
  43. jay | Oct 04, 2019
    We would wish a best of luck to you because such pages allow you to keep in touch with your users, honestly, I appreciate your welcome page. innosilicon a4+ tuotrial 
  44. bilal khan | Oct 04, 2019
    Great to progress toward becoming visiting your weblog once more, it has been a very long time for me. Pleasantly this article i've been sat tight for such a long time. I will require this post to add up to my task in the school, and it has identical subject together with your review. Much appreciated, great offerTax Accountants
  45. saeed khatri | Oct 03, 2019
    I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. UnitedFinances offer 1000 loan online
  46. sdsd | Oct 02, 2019
    Good post but I was wondering if you could write a litte more on this subject? I’d be very thankful if you could elaborate a little bit further. Appreciate it! UnitedFinances get now online 1000 loan
  47. $500 loan same day from UnitedFinances.com | Oct 01, 2019
    Today, I was just browsing along and came upon your blog. Just wanted to say good blog and this article helped me a lot, due to which I have found exactly I was looking. $500 loan same day from UnitedFinances.com 
  48. max | Sep 30, 2019

    It's fitting time to make a few arrangements for the future and the time has come to be glad. 

    latest Nigerian news today

  49. saeed khatri | Sep 29, 2019
    Superior post, keep up with this exceptional work. It's nice to know that this topic is being also covered on this web site so cheers for taking the time to discuss this! Thanks again and again! http://www.dejurka.ru/articless/white-headline-text-web-design/ 
  50. bilal khan | Sep 28, 2019
    Stunning! This could be one unequivocal of the most productive regions We ave ever get together transversely over as for this issue. Genuinely Excellent. I am in addition an expert in this subject so I can comprehend your exertion.Walnoten

    Leave a comment