Update the handlebars template following an ajax response

Within my handlebars template, there is a specific div that is designated for displaying flash messages as shown below:

<div id="flashContainer" class="alert alert-dismissible alert-{{flash.type}}" style="display: {{#if flash}}block {{else}}none{{/if}}">
    <button type="button" class="close"
            data-dismiss="alert" aria-hidden="true">&times;</button>
        <strong>{{flash.intro}}</strong> {{{flash.message}}}
</div>

After initiating an ajax request by submitting a form, the goal is to dynamically update this flash message section upon successful completion of the request. The aim is to avoid manually editing the HTML and instead re-render only the specified part of the template above. How can I accomplish this task using handlebars and expressJS?

Answer №1

If you prefer to separate your ajax response template and only render it after receiving the response.

Alternatively, if you wish to keep everything in one template and append it to the page just once, Handlebars does not have native support for this as it focuses on creating logic-less templates and working with strings rather than DOM elements. You can achieve this by using a helper with Handlebars, or explore other popular templating solutions that might better suit your needs, such as searching for data binding templates.

If Handlebars is your preferred option, I have developed a custom helper that could be of use to you. Check out post-render-bars and its renderer helper. Take a look at this demo to see how it renders an ajax response.

The helper makes use of the MutationObserver, refer to this browser support information, and consider using webcomponents-lite for a polyfill if necessary.

A quick overview of the relevant code snippets:

watch.js introduces a function forHtml(html, callback) that triggers a callback when the specified html is found in the DOM, temporarily assigning a unique class to the html.

helpers.js defines the helper renderer and the function createRenderer(getHtmlContentFn) which encapsulates your function into a renderer ready to be passed into a template as an argument for the helper.

The helper utilizes the watch.forHtml function to monitor the block defined by the helper and connects it with the renderer. Each time the renderer function is executed, the relevant DOM element is updated accordingly.

Here's a condensed version of the provided example, starting with the template:

<p>Below is the Ajax response:</p>
{{#renderer response}}<div>Loading...</div>{{/renderer}}

Followed by the JavaScript code:

var context = {
    response: postHandlebars.createRenderer(function(data) {
        return data;
    });
};
var html = template(context);
// append the html somewhere to visualize the response

$.ajax({
    type: 'GET', 
    url: 'some url'
}).done(context.response);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with error handling in Js Node Selenium Try-Catch? Let's troubleshoot

My goal is to simulate the action of clicking on an element that is displayed after a specific iteration of document.readyState = 'complete'. To overcome the readyState issue, I considered using try-catch with the executeScript command to keep re ...

Cookie-powered JavaScript timer ceases after 60 seconds

I'm having an issue with my countdown timer where it stops counting after just one minute. It seems to pause at 54:00 when I set it for 55 minutes, and at 1:00 when I set it for 2 minutes. Any suggestions on how I can resolve this and make it continue ...

What is the best way to trigger a function when a button is enabled in Angular 8?

Here is a portion of my sign-in.component.html file. I have created a function in the corresponding sign-in.component.ts file that I want to trigger when the button below becomes enabled. Here is an example of what I am trying to achieve: <div class= ...

Firebase Cloud Function: Issue with multipart/form-data causing an "Unexpected end of form" error

I have been attempting to set up a file upload route on my Cloud Function Express app but have encountered an issue with the "Unexpected end of form at Multipart._final" error while running the server with firebase emulator. This error persists when test ...

Gallery Pagination using JQuery is not working properly

I am experimenting with the jquery easy paginate plugin on a separate page of my Blogspot. The images are displaying properly, but the pagination and CSS are not showing up. I need to adjust my CSS to make this jQuery pagination work correctly. Can someone ...

Finding the least common multiple (LCM) of two or three numbers using JavaScript

I have been working on a code snippet to find the Greatest Common Denominator (GCD) of two or three numbers. Here is what I have so far: Math.GCD = function(numbers) { for (var i = 1 ; i < numbers.length ; i++){ if (numbers[i] || numbers[i] = ...

I keep encountering this issue while attempting to retrieve information from an SQL server on a website

Error: There was an issue with the query. The table 'jeanpaulcaruana1bsc5m.tbl_' does not exist. PHP require_once("connection.php"); $connection = connectToMySQL(); $query = "select * from tbl_ members"; $result = mysqli_query($connection, $qu ...

Tips for creating multiple full-screen overlays in HTML

I am new to the world of web development and I am currently working on implementing a set of buttons that will trigger specific overlays when clicked. I found the following code snippet on W3schools which creates a button along with an overlay effect. < ...

Having trouble using the `.not` function in jQuery

I'm working on implementing a collapsible menu using jQuery. When any header is clicked, the next sibling (the box) should expand while all other boxes collapse. HTML <div class="finbox" id="finbox1"> <div class="finheader" id="finheade ...

Steps for launching an audio fileHow to start playing an audio

I am trying to automatically play an audio file audio when the window opens by using the playaudio() function. How can I achieve this? window.onload = function(playAudio();) var audio = new Audio("https://s3.amazonaws.com/audio-experiments/examples/el ...

The javascript code appears to be functioning properly on desktop browsers but is not functioning as expected on Chrome's mobile browser

On my WordPress site, I have created a Java Bootstrap loan calculator that works perfectly on desktop. However, when I use Chrome on mobile, it is not functioning properly. I tried using the wp-coder plugin and also manually added the necessary code. Int ...

What is the method to invoke a function within another function in Angular 9?

Illustration ` function1(){ ------- main function execution function2(){ ------child function execution } } ` I must invoke function2 in TypeScript ...

Storing a temporary value within an ng-repeat iteration in AngularJS

A unique and interesting query arises when dealing with random value generation. Here is a snippet of code that showcases how to achieve this: function randomize() { return function (input) { if (input !== null && input !== undefined & ...

Interested in trying out Express and socket.io for chatting?

I've successfully set up the chat application, but now I'm faced with a dilemma: how can I make the chat work on the default port:80, where my main site is hosted? One solution that comes to mind is using an iframe - but is there another way? B ...

Having trouble rendering to the framebuffer due to issues with the texture

In the process of incorporating shadow maps for shadows, I am attempting to render a scene to a separate framebuffer (texture). Despite my efforts, I have not been able to achieve the desired outcome. After simplifying my codebase, I am left with a set of ...

Transferring data between different elements in a React application

I am currently learning React and facing some challenges in terms of passing data between components. Even after reviewing various tutorials and blogs, I am still struggling to make things work. Within my project, I have two child components named Body-c ...

Tips for effectively overlaying one container on top of another in a responsive manner

There are a pair of containers. The main container functions as the parent, while the child container acts as a tag to categorize the content. The objective is to position the tag container at the top right corner of the main content container, slightly of ...

Tallying responses of "Yes" and "No" in a React form and storing them

I'm currently working on a React form using Material UI components. To keep track of the responses, I have an empty array called questionAns. My goal is to append an element like yes to the array when the Yes radio button is selected in the form. Belo ...

Ways to merge values across multiple arrays

There is a method to retrieve all unique properties from an array, demonstrated by the following code: var people = [{ "name": "John", "age": 30 }, { "name": "Anna", "job": true }, { "name": "Peter", "age": 35 }]; var result = []; people. ...

I'm receiving a typeerror when trying to access the uid property of null, even though I don't have any asynchronous code and the users are logged

I am currently working on developing a user profile edit page that redirects users to their unique profile after logging in. However, I keep encountering an error that says Uncaught (in promise) TypeError: Cannot read properties of null (reading 'uid& ...