load_ajax_template

Loads a webstore template within an another webstore template, using AJAX to either defer loading or refresh page content without the need to refresh the entire page. Note, AJAX loaded templates are not cached the same as other content and should only contain the dynamic content you wish to update. Do not include large blocks of static content in an AJAX template as this would benefit more from caching.

Example

[%load_ajax_template id:'_header' type:'item' template:'header' preload:'1' tmpl_sku:'[@current_sku@]' tmpl_preview:'y'/%]

Usage

The load_ajax_template function comes in two parts, a B@SE function tag to determine what content should be AJAX loaded and where it should be placed, and a JS function to trigger the AJAX refresh and reload the template with the latest data.

Add loader for the AJAX template

Add the [%load_ajax_template%] function to an existing template, where you would like the AJAX loaded content to display. General convention for the id is to use the name of the AJAX template with an underscore at the front. For example to load in product header details on the main product template you could use:

[%load_ajax_template id:'_header' type:'item' template:'header' preload:'1' tmpl_sku:'[@current_sku@]' tmpl_preview:'y'/%]

Reload the AJAX template

Generally you would want your AJAX content to refresh after a customer has performed a certain action. This can be done by triggering the $.load_ajax_template() function in a JS script or event handler. For example, to load in more brands, you might trigger a refresh on a button press:

[%load_ajax_template id:'_ajax_brands' type:'content' template:'ajax_brands' preload:'1' tmpl_preview:'y'/%]
<button class="btn btn-outline-secondary" onclick="$.load_ajax_template('_ajax_brands')">Load More Brands</button>

Need to do additional script evaluations or pass additional params/data tags through with the AJAX request? Place the $.load_ajax_template() function in a script tag to run more advanced code. The below code grabs the current pagination value, increments it, then AJAX loads the new page contents, passing on the page Content ID and Total Pages as additional variables.

<!-- /httpdocs/assets/themes/[THEME-NAME]/templates/cms/brands.template.html -->
[%load_ajax_template id:'_ajax_brands' type:'content' template:'ajax_brands' preload:'1' tmpl_page:'1' tmpl_preview:'y'/%]
<!-- /httpdocs/assets/themes/[THEME-NAME]/templates/cms/includes/ajax_brands.template.html -->
[%set [@current_page@] %][%if [@ajax_pgnum@]%][@ajax_pgnum@][%else%][@page@][%/if%][%/set%]
[%thumb_list type:'content' content_type:'brand' limit:'[@config:THUMB_LIMIT@]' filter_category:'' sortby:'content_name' pgnum:'[@current_page@]'%]
    [%param *header%]
        <div class="row align-items-center">
    [%/param%]
    [%param *body%]
            <div class="brand-item mb-3 text-center col-6 col-md-4 col-lg-3">
                <a href="[@URL@]">
                    <img class="img-fluid" src="[%ASSET_URL type:'content' id:'[@content_id@]'%][%param default%][%cdn_asset html:'0' library:'images'%]default_product.gif[%/cdn_asset%][%/param%][%/ASSET_URL%]" alt="[@name@]"/>
                    [@name@]
                </a>
            </div>
    [%/param%]
    [%param *footer%]
        </div>
        <p>Page [@current_page@] of [@total_pages@]</p>
        [%if [@current_page@] < [@total_pages@] %]
            <button class="btn btn-outline-secondary" onclick="updateBrands([@current_page@])">Load More Brands</button>
            [%site_value id:'footer_javascript'%]
                <script>
                    function updateBrands(currentPage){
                        currentPage++;
                        let nextPage = currentPage;
                        $.load_ajax_template('_ajax_brands',{showloading: '1', ajax_pgnum: nextPage, content_id: '[@content_id@]', total_pages: '[@total_pages@]'});
                    }
                </script>
            [%/site_value%]
        [%/if%]
    [%/param%]
    [%param *ifempty%]
        <div class="row align-items-center">
            <p>Sorry, we don't have any brands that match your search. <a href="[%url type:'page' id:'[@content_id@]'%][%/url%]">View All Brands</a></p>
        </div>
    [%/param%]    
[%/thumb_list%]

JavaScript Function Parameters

The $.load_ajax_template() function has three parameters which can be configured to build out more complicated and custom webstore functionality.

Name Options Description
`AJAX Template ID` String *required The unique identifier for the AJAX template, this should be the same as the `[%load_ajax_template%]` function `id` param, e.g: `$.load_ajax_template('_header');`
`Additional Options` JS Object, values inside can be JS variables containing Strings, Integers, or Floats. B@SE tags, or hardcoded *optional Include any data tags required for your AJAX template to function here. Multiple tags can be added using a comma separated list, e.g: `$.load_ajax_template('_header',{sku: 'INV001', content_id:42});`.
Values defined here will be available as B@SE tags in the AJAX template: `[@sku@]` = 'INV001' and `[@content_id@]` = 42. Please note, B@SE tags cannot parse JS arrays or complex objects.
Want to show a loading overlay when the AJAX template is triggered, add `showloading: '1'` as one of the additional options.
`Callback Function` JS Function *optional If you need to run something after the AJAX template has loaded you can do so by supplying a callback function as the last parameter. If you are running a callback function without any Additional Options you must provide an empty JS Object as the functions second param to then declare the callback function.

Callback Function Example

$.load_ajax_template("_ajax_products", {}, {
    onLoad: function(templateContent){
        // This function will be executed once the AJAX template has fully loaded
        // The contents of the loaded template can be accessed via templateContent, as a string
        // For example, to return the number of thumbnails generated by the AJAX template
        console.log("AJAX template loaded: " + templateContent);
        const parser = new DOMParser();
        const ajaxDoc = parser.parseFromString(templateContent, 'text/html');
        const newProducts = ajaxDoc.querySelectorAll(".thumbnail");
        console.log(`Number of thumbnails loaded: ${newProducts.length}`);
    }
});

B@SE Function Parameters

Name Options Description
`id:''` String Unique ID of the AJAX template, used by the load_ajax_template JS function to load a corresponding `[%load_ajax_template%]` code block
`type:''` `cart`, `item`, `content` The type of content you want to AJAX load, some params will only work for certain types
`template:''` Template HTML file name, excluding the .template.html extension Determines what HTML file to load, this template file must be located in the `includes` folder of the corresponding `type`. For example:
`cart/includes/`, `products/includes/`, `cms/includes/`
`preload:''` `1`/`0` If set, the AJAX template will render along with the rest of the templates on initial page load - AJAX won't be used for this initial load but can be used after to reload the template. Set this to `0` if you wanted to hide the AJAX contents until an action has been performed to reload it.
`tmpl_sku:''` Product SKU Works with type `item`, defines which product is in scope when the AJAX template runs
`tmpl_preview:''` `y`/`n` When set to 'y', calls the AJAX template file with the equivalent of "?preview=y" in the URL. This allows AJAX content to be returned on the page when a product is unapproved and you view it from the control panel, or are using `?preview=y` in the URL for testing
`tmpl_x:''` String or B@SE tag Need to pass a value from the main template through to the preview AJAX template? Set it using `tmpl_x` where `x` is the name of the B@SE tag in the AJAX template. E.g: `tmpl_custom:'yes'` would allow you to add the `[@custom@]` tag to the AJAX template and print "yes". Tags set this way will persist when the AJAX template refreshes unless you change them when `$.load_ajax_template()` is called

Was this article useful?

Be notified when this page is updated. Optional.