Loading the bvapi.js API asynchronously

All Bazaarvoice content except the API loader file bvapi.js is loaded asynchronously.

If you must load content asynchronously, do not include the bvapi.js script tag directly in your HTML pages. Include the bvapi.js script in one of the following script blocks instead:

  • If you use jQuery, include the following block:

    <script type="text/javascript">
        var bvapiUrl = window.location.protocol + "//default.ugc.bazaarvoice.com/bvstaging/static/1235-en_us/bvapi.js";
        
        window.loadBazaarvoiceApi = function(callback) {
            if (window.$BV) {
                callback();
            } else {
                $.ajax({
                    url: bvapiUrl,
                    cache: true,
                    dataType: "script",
                    success: function() {
                        $($BV.docReady);
                        callback();
                    }
                });
            }
        };
    </script>
    
  • If you do not use jQuery, include the following JavaScript:

    <script type="text/javascript">
        (function() {
            var bvapiUrl = window.location.protocol + "//default.ugc.bazaarvoice.com/bvstaging/static/1235-en_us/bvapi.js"; 
        
            function getScript(url, callback) {
                var head = document.getElementsByTagName("head")[0] ||
                    document.documentElement,
                    script = document.createElement("script");
                script.src = url;
                script.type = "text/javascript";
                script.charset = "utf-8";
                script.setAttribute("async", "async");
                script.onload = script.onreadystatechange = function () {
                    if (!this.readyState || this.readyState === "loaded" ||
                        this.readyState === "complete") {
                        script.onload = script.onreadystatechange = null;
                        callback();
                    }
                };
                head.insertBefore(script, head.firstChild);
            }
        
            // work around Firefox 3.0, 3.5 lack of document.readyState
            // property.
            // Note: Because of this workaround, the <script> fragment must
            // be included within the <head> or <div> element so that it
            // executes before the window load event is fired.
        
            var docReady, onDocReady = function(){docReady = true;};
            if (document.readyState === undefined && document.addEventListener)
            {
                document.addEventListener("DOMContentLoaded", onDocReady, false);
                window.addEventListener("load", onDocReady, false);
            }
        
            window.loadBazaarvoiceApi = function(callback) {
                if (window.$BV) {
                    callback();
                } else {
                    getScript(bvapiUrl, function() {
                    if (docReady) {
                        $BV.docReady();
                    }
                    callback();
                    });
                }
            };
        })();
    </script>
    

All subsequent calls to Bazaarvoice API functions, such as $BV.ui(), are wrapped in loadBazaarvoiceApi calls, as the following example shows:

loadBazaarvoiceApi(function() {
    $BV.ui("rr", "show_reviews", { productId: "test1" });
});

Implementing inline ratings

Including inline ratings on category or search pages provides useful summary information to consumers who are researching or comparing products. Inline ratings helps consumers select which products they want to view or which PDPs they want to drill down into.

Inline ratings code allows you to display:

  • Star rating images
  • Decimal value for the overall average rating (for example, 4.5)
  • Number of reviews (for example, 116)

You can implement inline ratings using two different methods:

Method comparison

Comparison Conversations API Ratings-only export feed
Level of development effort Lower Higher
Statistics freshness Real-time updates Updated daily (potentially out-of-sync with stats on product page)
Local repository of statistics for use in other advanced areas such as faceted navigation or use in search results algorithms. No Yes
Format XML or JSON XML only

Inline star ratings help your customers to research and compare products. The Conversations API provides a highly optimized API method for retrieving review statistics such as average rating.

This method has been specifically built to handle high intensity applications such as search results pages and product category listing pages.

For example, you can call the Conversations API for each desired product ID as a search results page is being rendered.

  • There is no need to cache these statistics locally prior to rendering the page.
  • There is no need to store a local copy of the star images. Bazaarvoice can host the star images.
  • This method gives you the flexibility to display the rating and images as you desire.
Note: Statistics returned by statistics.json/xml are global statistics calculated on the entire reviews set for a product across all locales. Contact Bazaarvoice Client Care if locale-specific statistics are required.
  1. To request production and staging keys for the Conversations API, follow the Key Request Process .
  2. To request review statistics, use the appropriate product ID to call the Conversations API:
  3. Map the overall ratings value (rounded to one decimal place) returned in the API response to link to the appropriate Bazaarvoice-hosted star image URL.
    • Image URL pattern:

      http://default.ugc.bazaarvoice.com/1235-en_us/[overall rating value]/[max rating:5]/rating.gif
      

      The following example retrieves the star image for 3.1 out of 5 stars:

      http://default.ugc.bazaarvoice.com/1235-en_us/3_1/5/rating.gif
      
  4. Use the API response and star image to display the inline rating image and overall rating value as needed on your category or search listing page.

Method 2: Display inline ratings using the ratings-only export XML feed

Inline star ratings help your customers to research and compare products. The ratings-only export feed is a daily XML-based export of product specific, ratings related content, including a series of star images. These star images represent rating values that range from 0.0 through 5.0 and are incremented by tenths.

  1. Store the images from the Bazaarvoice XML ZIP file on your server.
  2. Download the Bazaarvoice ratings-only export feed and perform one of the following steps:
    • Store the feed on your server for direct referencing for the rating and review count.
    • Insert the overall rating and review count into your database.
  3. Use the appropriate product ID to look up the following values in the static file or local database:
    • Overall ratings
    • Number of reviews
  4. Map the overall rating value in the database to the appropriate star image file. For example, if the overall rating value is 3.7, map it to the star image file named rating-3_7.gif.

For more information, refer to the ratings-only export feed topic.

Implement login redirection using JavaScript (site authentication)

Bazaarovice recommends implementing hosted authentication. However, if building the hosted implementation redirection logic is too costly or not technically feasible, follow these instructions to implement site authentication.

Note: Be aware that using site authentication might briefly present a blank page before redirecting consumers to the signin page. It may not provide the most optimal user experience.
  1. Place the following example code in the head section of every page where you want to display Bazaarvoice content:

    <script type="text/javascript"
        src="//default.ugc.bazaarvoice.com/bvstaging/static/1235-en_us/bvapi.js">
    </script>
    <script type="text/javascript">
        $BV.configure("global", {
            userToken: "XXXXX",
            doLogin: function(successCallback, successUrl) { 
                window.location = "http://www.client.com/login.html?return=" + encodeURIComponent(successUrl);
            }
        });
    </script>
    

    XXXXX represents the Bazaarvoice encoded user authentication string (UAS). Refer to generating the user authentication string for more information. If an appropriate value is unavailable, leave this value blank.

  2. Replace the value of doLogin with the function that is called when Bazaarvoice requires user authentication.

After a successful login attempt on a separate page, the user is redirected back to the value of successUrl.

Integrate using AJAX-type login methods

successCallback can be executed if an AJAX-type login method is used and the user is still on the submission container page.

  1. Place the following example code in the head section on every page that you want to display Bazaarvoice content.

    <script type="text/javascript"
        src="//default.ugc.bazaarvoice.com/bvstaging/static/1235-en_us/bvapi.js">
    </script>
    <script type="text/javascript">
        $BV.configure("global", {
            userToken: "XXXXX",
            doLogin: function(successCallback, successUrl) { 
                myExampleAjaxLogin(function myExampleAfterLogin(encoded_user_string) {
                    successCallback(encoded_user_string); 
                });
            },
        });
                    </script>
    

    XXXXX represents the Bazaarvoice user authentication string (UAS). If an appropriate value is unavailable, leave this value blank.

  2. Replace the value of doLogin with the function that is called when Bazaarvoice requires user authentication.
  3. After the user successfully logs in to the system, call successCallback and pass the UAS as the first parameter.

Display content that resides behind a tab

If Bazaarvoice content is hidden behind a tab or other UI element, implement a callback so that the content can be displayed under the appropriate conditions, such as targeted links to a specific review or question or answer content.

To implement such a callback, define the doShowContent option in the appropriate show_* $BV.ui() call, as shown by the following example code.

<script type="text/javascript">
    $BV.ui("rr", "show_reviews", {
        productId: "XXXXX",
        doShowContent: function() { 
            myExampleShowTab("#ReviewsTab"); 
        }
    });
</script>

Although the preceding example code refers to a Ratings & Reviews integration, the doShowContent function applies to all feature integrations.

Bazaarvoice calls the function that is specified by doShowContent, so in the previous example, this function calls myExampleShowTab.

  • doShowContent supports asynchronous operations. A common need for such operations involves the inclusion of functions from popular JavaScript libraries, such as jQuery.
  • The function can be configured with callbacks to prevent the occurrence of actions that are based on content focusing. For example, returning a value of false from doShowContent prevents it from scrolling to content, as the following code shows.
function doShowContent(application, displayCode, subject, deepLinkId, callback, source ) {
    if ( I want to scroll ) {
        myExampleAsyncShowTab('#exampleReviewsTab', { onFinish: callback });
        return false;
    }
    else {
        return false;
    }
}

The following table identifies possible values for the source object. Use thes following values to prevent specific content-focusing actions, depending on the events that trigger them.

Value Content focusing is called by
readLink A Read XXXX link
deepLink A targeted URL
submission Returning from the submission flow

Implement same-page submission

Same-page submission allows you to use a single page for the display and submission of user-generated content.

The following topics describe the JavaScript functions that handle login duties, populate the submission iframe element, and manage the page display:

  • AJAX-type login method
  • Separate login page

Implement same-page submission with AJAX-type login methods

Although Bazaarvoice supports same-page submission, additional configuration options must be defined to account for all user interactions, including interactions that involve login integration.

Even if same-page submission is enabled, it’s recommended that you build a standalone submission container to drive the submission of UGC during email campaigns.

The following example code provides a stub of the code that must be implemented to support same-page submission with an AJAX-type login method.

<script type="text/javascript">
    $BV.configure("global", {
        allowSamePageSubmission: true,
        userToken: "XXXXX",
        doLogin: function(successCallback, successUrl) { 
            myExampleAjaxLogin(function myExampleAfterLogin(encoded_user_string) {
                successCallback(encoded_user_string); 
            });
        },
        doShowSubmission: function() {
            myExampleShowLightbox("Submission_Lighbox");
        },
        onSubmissionReturn: function() {
            myExampleCloseLightbox("Submission_Lighbox");
        },
        doScrollSubmission: function() {
            myExampleScrollToSubmission();
            return false;
        }
    });
</script>

Make the following changes to this code:

  1. Replace the userToken value of XXXXX with the Bazaarvoice encoded UAS. If you don’t have a value to place in this location, leave it blank.
  2. Replace the value of doLogin with a function of your design. Bazaarvoice calls this function when user authentication is required, provided the value of userToken is blank or not set.
  3. After a successful login attempt, call successCallback and pass the UAS as the first parameter.
  4. Replace the value of doShowSubmission with a function of your design. Bazaarvoice calls this function before the submission form loads. This function can be used to show lightboxes or to switch to the tab into which the submission form must load.
  5. Replace the value of onSubmissionReturn with a function of your design. Bazaarvoice calls this function after submission is completed. This function can be used to close lightboxes or to switch away from the tab into which the submission form was loaded.
  6. Replace the value of doScrollSubmission with a function of your design. Bazaarvoice calls this function after the submission form is displayed or updated. This function can be used to prevent the default scrolling behavior by returning false.
  7. Place the following div element where you want the submission form to load on your product or category page.

    <div id="BVSubmissionContainer"></div>
    

    Alternatively, to load the submission form into a different div element, such as the div in which the main Bazaarvoice content loads, override the submission div name as shown by the following example for Ratings & Reviews.

    $BV.ui("rr", "show_reviews", {productId: "A1234", submissionContainerDiv: "BVRRContainer"});
    

When this code is used in conjunction with the example $BV.configure, “Write a review” links cause the submission form to load in the location that displays the main block of reviews.

Note: $BV.configure calls must be made prior to any $BV.ui calls that they affect.

Implement same-page submission with a separate login page

You can enable same-page submission in conjunction with a separate login page (as opposed to an AJAX-type login method). The following example code provides a stub of the code that must be implemented.

<script type="text/javascript">
    $BV.configure("global", {
        allowSamePageSubmission: true,
        userToken: "XXXXX",
        doLogin: function(successCallback, successUrl) { 
            window.location = "http://www.client.com/login.html?return=" + encodeURIComponent(successUrl);
        },
        doShowSubmission: function() {
            myExampleShowLightbox("Submission_Lighbox");
        },
        onSubmissionReturn: function() {
            myExampleCloseLightbox("Submission_Lighbox");
        },
        doScrollSubmission: function() {
            myExampleScrollToSubmission();
            return false;
        }
    });
</script>

Make the following changes to this code:

  1. Replace the userToken value of XXXXX with the Bazaarvoice-encoded UAS. If you do not have a value to place in this location, leave it blank.
  2. Replace the value of doLogin with a function of your design. Bazaarvoice calls this function when user authentication is required. Ensure that the function redirects the user to the login form.
  3. After a successful login attempt on a separate page, redirect the user back to the value of successUrl.
  4. Replace the value of doShowSubmission with a function of your design. Bazaarvoice calls this function before the submission form loads. This function can be used to show lightboxes or to switch to the tab into which the submission form must load.
  5. Replace the value of onSubmissionReturn with a function of your own design. Bazaarvoice calls this function after submission is completed. This function can be used to close lightboxes or to switch away from the tab into which the submission form was loaded.

    onSubmissionReturn is called only when the user is not redirected to the login page prior to submission. If the user is redirected, onSubmissionReturn is not called. Instead, the page is refreshed with the URL before the user is redirected to the login page. Define submissionReturnUrl to override this URL.

  6. Replace the value of doScrollSubmission with a function of your design. Bazaarvoice calls this function after the submission form is displayed/updated. This function can be used to prevent the default scrolling behavior by returning false.
  7. Place the following div element where you want the submission form to load on your product or category page.

    <div id="BVSubmissionContainer"></div>
    

    Alternatively, to load the submission form into a different div element, such as the div in which the main Bazaarvoice content loads, override the submission div name as shown by the following example for Ratings & Reviews.

    $BV.ui("rr", "show_reviews", {productId: "A1234", submissionContainerDiv: "BVRRContainer"});
    

    When this code is used in conjunction with the example $BV.configure, “Write a review” links cause the submission form to load in the location that displays the main block of reviews.

Note: $BV.configure calls must be made prior to any $BV.ui calls that they affect.

Implement same-page submission (additional options)

Although Bazaarvoice supports same-page submission, additional configuration options must be defined to account for all user interactions.

Even if same-page submission is enabled, it’s recommended that you build a standalone submission container to drive the submission of user-generated content during email campaigns.

The following example code provides a stub of the code that must be implemented to support same-page submission.

<script type="text/javascript">
    $BV.configure("global", {
        allowSamePageSubmission: true,
        doShowSubmission: function() {
            myExampleShowLightbox("Submission_Lighbox");
        },
        onSubmissionReturn: function() {
            myExampleCloseLightbox("Submission_Lighbox");
        },
        doScrollSubmission: function() {
            myExampleScrollToSubmission();
            return false;
        }
    });
</script>

Make the following changes to this code:

  1. Replace the value of doShowSubmission with a function of your design. Bazaarvoice calls this function before the submission form loads. This function can be used to show lightboxes or to switch to the tab into which the submission form must load.
  2. Replace the value of onSubmissionReturn with a function of your design. Bazaarvoice calls this function after submission is completed. This function can be used to close lightboxes or to switch away from the tab into which the submission form was loaded.
  3. Replace the value of doScrollSubmission with a function of your design. Bazaarvoice calls this function after the submission form is displayed/updated. This function can be used to prevent the default scrolling behavior by returning false.
  4. Place the following div element where you want the submission form to load on your product or category page.

    <div id="BVSubmissionContainer"></div>
    

    Alternatively, to load the submission form into a different div element, such as the div in which the main Bazaarvoice content loads, override the submission div name as shown by the following example for Ratings & Reviews.

    $BV.ui("rr", "show_reviews", {productId: "A1234", submissionContainerDiv: "BVRRContainer"});
    

When this code is used in conjunction with the example $BV.configure, “Write a review” links cause the submission form to load in the location that displays the main block of reviews.

Note: $BV.configure calls must be made prior to any $BV.ui calls that they affect.

Track events using the event callback

You can track certain actions that occur within Bazaarvoice UI components by using the Bazaarvoice JavaScript event callback. For example, the event callback can be used to pass tracking information into your analytics solution.

Common uses for the JavaScript event callback include:

  • Viewing the average rating and review count of a product while a user views the page. This information helps to establish a relationship between the rating or review count and the conversion rate of a product.
  • Tracking the progress of a submission form and rates of abandonment.
  • Dynamically generating portions of a page based on information that the hooks provide, such as the current phase of the submission process.

Event callback example

To use the event callback, specify the onEvent option when making $BV API calls, as the following example shows.

<script type="text/javascript">
    $BV.ui("rr", "show_reviews", {
        productId: "XXXXX",
        onEvent: function(json) { 
            if (json.eventSource == "Action") {
                myExampleAnalyticsTrackEvent("Bazaarvoice interaction happened");
            }
        }
    });
</script>

Event variables for Ratings & Reviews

The following table identifies the specific variables that are associated with the attributes variable in Ratings & Reviews.

Variable Value Description
numReviews Integer Total number of approved reviews that are submitted on the product.
numRatingsOnlyReviews Integer Number of ratings-only reviews that are submitted on the product. By default, a ratings-only review contains fewer than 50 characters of review text and features no attached photos, videos, user entered tags, or additional user entered fields.
percentRecommend Integer (0-100) Percentage of users who selected Yes as an answer to the question "Would you recommend this product to a friend?"
avgRating Float Average rating of the product, expressed in a format that displays up to four decimal places.

Ratings & Reviews example

<script type="text/javascript">
    $BV.ui("rr", "show_reviews", {
        productId: "XXXXX",
        onEvent: function(json) { 
            alert(json.attributes.numReviews);
        }
    });
</script>

Event variables for Questions & Answers

The following table identifies the specific variables that are associated with the attributes variable in Questions & Answers.

Variable Value Description
numQuestions Integer Total number of approved questions that are submitted about the subject.
numAnswers Integer Total number of approved answers that are submitted about the subject.

Questions & Answers example

<script type="text/javascript">
    $BV.ui("qa", "show_questions", {
        productId: "XXXXX",
        subjectType: "product",
        onEvent: function(json) { 
            alert(json.attributes.numQuestions);
        }
    });
</script>

Event variables for Bazaarvoice products

The following table identifies the specific variables that are associated with the attributes variable in all Bazaarvoice products.

Variable Value Description
mediaType String Indicates that a visitor clicked hosted media within a piece of Bazaarvoice content. Possible values are photo and video.
filterType String

Indicates that a visitor clicked Filter By or Sort By and then selected a filter. Possible values are as follows:

  • Date – Newest First
  • Expert Reviews First
  • Photo Reviews First

Example

<script type="text/javascript">
    $BV.ui("qa", "show_questions", {
        productId: "XXXXX",
        subjectType: "product",
        onEvent: function(json) { 
            alert(json.attributes.numQuestions);
        }
    });
</script>

Additional “analytics” event variables

The following table identifies some of the additional analytics variables that you can use.

Variable Values Description
attributes Specific to your Bazaarvoice feature or features See previous sections.
bvProduct RatingsAndReviews Current feature is Ratings & Reviews.
AskAndAnswer Current feature is Questions & Answers.
eType Read Content is available for the user to view.
Write User is engaged with the content-submission process.
Support User is engaged with additional submission processes, such as providing feedback or reporting content as inappropriate.
eventSource Display JavaScript Event API was invoked by injection.
Action JavaScript Event API was invoked by a user click or other action.
eventTarget Review Action is being performed on a review.
Question Action is being performed on a question.
Answer Action is being performed on an answer.
Comment Action is being performed on a comment.
Profile Action is being performed on a profile.
Story Action is being performed on a campaign item.
leafCategoryId Alphanumeric External ID of the category.
pageType (submission only) Input User is viewing the submission form.
Preview User is viewing the Preview page.
Confirm User is viewing the Thank You page or another end-result page.
pageStatus (submission only) Cancelled User cancelled the submission process.
AuthenticationFailure Valid UAS was not passed to Bazaarvoice.
Expired User's submission session expired.
AlreadySubmitted User attempted to submit duplicate content soon after the original submission.
Own User attempted to submit helpfulness feedback for own content.
Duplicate User attempted to submit helpfulness feedback for content for which he or she has already submitted feedback.
ValidationError User attempted to submit content that does not pass validation.
productId Alphanumeric External ID of the product.
rootCategoryId Alphanumeric External ID of the top-level category parent.
Variable Values Description
attributes Specific to your Bazaarvoice product or products See previous sections.
bvProduct RatingsAndReviews Current product is Ratings & Reviews.
AskAndAnswer Current product is Questions & Answers.
Stories Current product is campaigns.
Profiles Current product is profiles.
eType Read Content is available for the user to view.
Write User is engaged with the content-submission process.
Support User is engaged with additional submission processes, such as providing feedback or reporting content as inappropriate.
eventSource Display JavaScript Event API was invoked by injection.
Action JavaScript Event API was invoked by a user click or other action.
eventTarget Review Action is being performed on a review.
Question Action is being performed on a question.
Answer Action is being performed on an answer.
Comment Action is being performed on a comment.
Profile Action is being performed on a profile.
Story Action is being performed on a campaign item.
leafCategoryId Alphanumeric External ID of the category.
pageType (submission only) Input User is viewing the submission form.
Preview User is viewing the Preview page.
Confirm User is viewing the Thank You page or another end-result page.
pageStatus (submission only) Cancelled User cancelled the submission process.
Expired User's submission session expired.
AlreadySubmitted User attempted to submit duplicate content soon after the original submission.
Own User attempted to submit helpfulness feedback for own content.
Duplicate User attempted to submit helpfulness feedback for content for which he or she has already submitted feedback.
ValidationError User attempted to submit content that does not pass validation.
productId Alphanumeric External ID of the product.
rootCategoryId Alphanumeric External ID of the top-level category parent.

Contact Bazaarvoice Client Care to obtain a comprehensive list of analytics variables.

Examples

The following code runs whenever each page of the submission process loads, such as the Edit, Preview, or Submit page.

<script type="text/javascript">
    $BV.ui("submission_container", {
        onEvent: function(json) { 
            if ( json.eventSource == "Display" && (json.eType == "Write" || json.eType == "Support") ) {
                alert("Submission step: " + json.pageType);
            }
        }
    });
</script>

The following code runs whenever a user clicks a link or performs another action in Ratings & Reviews.

<script type="text/javascript">
    $BV.ui("rr", "show_reviews", {
        onEvent: function(json) { 
            if ( json.eventSource == "Action" ) {
                alert("User click happened");
            }
        }
    });
</script>