Making an Asynchronous Call
All API calls are synchronous unless you specify an optional last parameter at the end of the function call. Below we'll show you how to make an asynchronous call.
Example of synchronous code
// Make the API call var shippingEstimates = estimateShipping(); // Consume the result for (var = i; i < shippingEstimates.length; i++){ // Do something with the estimate }
Example of asynchronous code
// Define a callback function function myCallbackFunction(shippingEstimates){ for (var = i; i < shippingEstimates.length; i++) { // Do something with the estimate } } // Make the asynchronous call estimateShipping({'async': true, 'onComplete': myCallbackFunction});
Our recommendation is to make the the shipping estimate call asynchronous due to the time it can take calculate estimates. Make sure that you give the customer a visual indication that shipping estimates are being calculated. We do not recommend making calls that manipulate the cart asynchronous as it could cause inconsistancies in the global cart variables contents.
In version 2, most methods also take an opts
method as their last parameter. This is short for 'options'. It's a hash that allows for asynchronous execution of the method.
The hash contains two keys: async and onComplete.
async: true | false
onCompelete: function
If you pass in true for async, and a function reference for onComplete, then the method will be executed asynchronously, and the onComplete method will fire upon success.
Here's an example where the checkout method is executed async with a success function (NOTICE LINE 3):
ultraCart.saveFieldElements(function () { // when the save finishes, initiate the checkout. do it asynchronously ultraCart.checkout(checkoutMethod || ultraCart.checkouts.CHECKOUT_ULTRACART, {async:true, onComplete:function(result) { // if the post is accepted, redirectToUrl will be populated. This doesn't mean everything was successfully, // only that basic validation passed. If there's any error, then the 'please wait' page will redirect back to this page // and the error parameter will be displayed. By using ultraCart.checkout(), the default error parameter name of 'ucError' is used. // see handleCheckoutErrors() if (result.redirectToUrl) { ultraCart.util.postGet(result.redirectToUrl); // post instead of redirect to discourage back button use. // if the validation failed, then show errors and reset the finalize button. } else if (result.errors) { finalizing = false; jQuery('#finalizeLink').html("<img src='images/finalizeOrder.gif' alt='Finalize Order'/>"); renderErrors(result.errors); // ?? this else block should never execute. } else { finalizing = false; } }}) });