Using JavaScript to manipulate JSTL tags: A step-by-step guide

Is there a way to handle JSTL tags (fmt:) within a JavaScript response-handler function? For instance:

  1. I am trying to switch languages via AJAX, therefore I need to update my tool panel using JavaScript and process fmt:setLocale in the response-handler function
  2. When updating select dropdown menus via AJAX for localization purposes, how can I utilize fmt:message in JavaScript?

However, the JSP engine does not handle .js files. This is causing issues with the following code:

document.findElementById("div1").innerHTML = "<fmt:message key="word_from_DB"/>";
document.findElementById("div2").innerHTML = "<fmt:setLocale value="en"/>";

Question: What are some alternative methods to process these tags from JavaScript or where should I look for solutions?

Answer №1

To achieve your desired outcome, the approach you take will depend on the specific content of your JSP and JS files. Here is a potential solution:

JS:

function updateDivContent(html1, html2) {
    document.findElementById("div1").innerHTML = html1;
    document.findElementById("div2").innerHTML = html2;
}

JSP:

...
<script>
updateDivContent("<fmt:message key="word_from_DB"/>", "<fmt:setLocale value="en"/>");
</script>
...

UPDATE based on feedback:

JSP (URL = "/cities"):

String country = request.getParameter("country");
String locale = request.getParameter("locale");
List<City> cities = getCitiesFromDB(country, locale);
out.println(objectToJSON(cities));

JS (using jQuery):

function addOption(value, text) {
    return $("<option></option>").html(text).val(value);
}

function displayCities(cities) {
    var $select = $("#city_select");
    $select.empty();
    for (var i = 0; i < cities.length; i++) {
        var $option = addOption(cities[i].name, cities[i].name);
        $select.append($option);
    }
}

function loadCities(country, locale) {
    var url = "/cities";
    return $.ajax(url, {
        data: {
            country: country,
            locale: locale
        }
    });
}

// invoke this method to fetch initial cities
// repeat the process when selecting a new country or locale
loadCities(country, locale).then(displayCities);

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

Efficiently communicating updates to clients after executing multiple HTTP requests simultaneously in RxJS

Objective: Execute multiple asynchronous HTTP requests simultaneously with RxJS and trigger a callback after each request is completed. For instance: fetchData() { Observable.forkJoin( this.http.get('/somethingOne.json').map((res:Re ...

What could be the reason for the page scrolling upwards when clicking on href="#"?

I am encountering an issue with a hyperlink <a href="#" id="someID">Link</a> that is located further down the page. This link is used to trigger an Ajax request, but whenever it is clicked, the page automatically scrolls back to the top. I have ...

Transferring form data to JavaScript for executing jQuery/AJAX request to fetch information from the database – what a journey!

Currently, I am attempting to extract a zip code from my form and then submit it to JavaScript/jQuery to retrieve data from the database associated with that specific zip code. After copying some code from w3schools and making a few modifications, as well ...

JavaScript Inferno" - Similar to the concept of "DLL Hell

I'm working on an ASP.NET webpage that has the following structure: <%@ Page Language="VB" MasterPageFile="~/LGMaster.master" AutoEventWireup="false" Inherits="com.Genie.PresentationLayer.Web.frmPNList" title="Primary Nominals results list - RESTR ...

Receiving a data response from AJAX in Node.js is easy with these steps

Right now, I am in the process of learning express, ajax, and nodejs. My current focus is on making ajax and nodejs communicate with each other. I have been sending a client request using ajax to a nodejs server. Everything seems to be working fine up unti ...

Issue with Vue Router not rendering components after dynamically importing them

I am facing an issue with vue-router while trying to register components dynamically. When I use hardcoded code, the router functions properly. However, when I load my routes dynamically, it fails to render the component. The component file is being impor ...

Creating a D3js line chart by inputting JSON data with d3.json

Since delving into the world of D3.js, I have encountered some challenges. Here is a summary of what I have experimented with so far: Below is my JavaScript code: d3.json("../js/sample2.json", function(data) { var canvas = d3.select("body").append("s ...

Avoid using the JQuery IIFE outside of the document ready function as it is considered a

Hey there! I've been coming across a puzzling "pattern" lately that doesn't sit well with me. The code seems messy and lacks clear structure. I've included a sample of the code for context. Is declaring all those IIFEs outside the document ...

The ng-change event is triggered for radio buttons that are generated using ng-repeat the first time they appear, but not for subsequent appearances

Is it possible to trigger the updateRow method on every change of a radio button selection? Currently, the updateRow method is only being called the first time the radio button changes. How can I make sure it executes each time there is a change? Html: ...

Is the V8 engine programmed to populate the call stack before executing the code, or does it execute the code upon entering a function?

Below is the code I attempted: // **Setting up variables and functions** let number_object = { num: 0 } function doWork(callback) { //Initiates work, expected to complete after 5 seconds console.log("working") setTimeout(() => { ...

What is the most efficient method for sending query parameters through a URL in Vue.js with Axios?

My goal is to use Axios upon page load to retrieve a JSON object from the base URL. When a button is clicked, I want to append query parameters to the URL and fetch a different JSON object. For example, if the base URL is 'test.com', clicking the ...

Deciphering the intricacies of VUEX-STORE modules

Consider this scenario: I have two separate lists - one for income and one for outcome. Each list has its own storage, and I am adding these storages as modules in index.js. While I could create a single repository for both income and outcome, displaying ...

When using Mongoose in Node, attempting to create an instance with a model may result in the error message "not a function."

Having trouble using my User model in the users.js route file. The error message "userModel is not a function" keeps popping up. Anyone have any insights on what could be causing this? Thanks! //Here's the code for my User model in models/user.js va ...

The error message I'm encountering is IntegrationError: The stripe.confirmCardPayment intent secret is invalid. The value must be a client_secret string

Currently, I am immersed in a tutorial for creating an Amazon clone using React JS. Everything was going smoothly until I encountered an issue after processing my orders. To handle the payment functionality, I am leveraging Stripe, Firebase, Axios, and Exp ...

Escaping Special Characters in JavaScript

My form is quite simple with two textboxes. When I click a button, I combine the contents of the textboxes using a delimiter. Is there a hidden delimiter that cannot be typed into an HTML textbox, even when using the &#xxx; syntax? ...

Transform the Angular function into a factory and take advantage of caching

My query differs from others with a similar title. I am attempting to transform a function into a factory in order to share data across controllers, but unlike my other factories, this one is not functioning as expected. I have successfully implemented ot ...

Navigating back to an Angular page from a non-Angular page using Protractor

Is there a specific method to return to an angular page? Below is the input and button code from an HTML (non-angular) page: <input class="value" type="password" 3dsinput="password" name="password"> <input type="submit" value="Submit" name="submi ...

SEO Friendly URL for JQuery Tabbed Content

I have developed a jQuery powered tabbed content system, where clicking on a tab changes the content below. However, I am facing an SEO issue. The SEO specialist has advised me to make it more SEO-friendly by adding different URLs to each tab. Can anyone ...

What is the process for configuring an HttpPost and specifying a header in JavaScript?

Every time I search for this question, I seem to find answers on how to set a header WITH JavaScript, but what I really want is to set the HttpPost Header FOR JavaScript. I am trying to log into a website, but I'm being told that I need to enable Jav ...

Combining arrays in Javascript without using the concat method

I am facing a challenge with merging two arrays. Most solutions I have come across suggest using the concat method. However, my requirement is to add a key/value pair from array1 to each object in array2. The first array (array1) that needs to be merged: ...