Any suggestions on how to incorporate the variable into the inline JavaScript [[]] API path?

I have a query regarding creating a URL in JavaScript, but I'm unsure how to include variables within th:inline="javascript". Below is my code snippet:

 <script th:inline="javascript">
 $(function() {
    $('#querySubmit').click(querySubmitClickAction);
    querySubmit.addEventListener('click', querySubmitClickAction);
    function querySubmitClickAction(e) {
        
        var theSize = 10;
        var name = $(this).val();
        $.ajax({
            url: /* 
[[@{/registeredUserList(type=0,userName=defaultName,page=0,size=10)}]]*/ 'dummy',
            type: 'POST',
            success: function (data) {
                $(".table_content").html(data);
            }
        })
     }
  });

How can I construct the URL using variables within the [[]]?

 url: /*[[@{/registeredUserList(type=0,userName=name,page=0,size=theSize)}]]*/ 'will show error',

Currently, it displays an error. How can I incorporate JS variables into the [[]] structure?

Thank you for your assistance.

Answer №1

To achieve this, follow these steps:

<script th:inline="javascript">
    /*<![CDATA[*/

    // Setting a JavaScript variable
    var mySize = 10;

    // Using Thymeleaf URL and ensuring proper formatting
    var myUrl = "[(@{/users/})]";

    // Creating a new URL object based on the current document location
    var url = new URL(myUrl, document.location);

    // Adding query parameters to the URL using JavaScript variables
    url.searchParams.append("size", mySize);

    console.log(url);

    /*]]>*/
</script>

When executed in the JavaScript console, the output will be:

http://localhost:3000/users/?size=10

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

How can I retrieve the width of a responsive React element during its initial rendering phase?

In my React project, there is a component called ResultList which is used to display products in a gallery format. The challenge I'm facing is determining the appropriate number of products to show per row based on the available width for the ResultL ...

In search of a screenplay that mirrors a specific scenario

I recently came across this website: One interesting feature is that all the content loads dynamically on the same page. Instead of loading separate pages, it pauses to fetch the content before smoothly scrolling to the correct section. ...

What is preventing the table from extending to the full 100% width?

Displayed above is an image showing an accordion on the left side and content within a table on the right side. I have a concern regarding the width of the content part (right side) as to why the table is not occupying 100% width while the heading at the ...

Ways to mix up a term while maintaining the original first and final characters intact (Javascript)

I've been given a task to shuffle a word that has more than 3 letters while keeping the first and last letters unchanged. The revised word should not be identical to the original, ensuring some sort of rearrangement is apparent. For example, when sh ...

Tips for successfully executing child_process.exec within an ajax request

On a server that I have access to but not ownership of, there is a node js / express application running on port 3000. Various scripts are typically executed manually from the terminal or via cron job. My goal is to have a button on the client-side that tr ...

Having trouble accessing the scrollHeight property of null when using Selenium WebDriver

I am currently working on a function in my code that is responsible for scrolling the page. This particular function was inspired by code used to scrape Google Jobs, which can be found here. However, I encountered an error that reads "javascript error: Ca ...

Discovering the Windows Identifier of the Opener Window in Chrome via JavaScript

I recently opened a link in a new window and realized that the current window's ID is now the ID of the newer window. I'm curious if there is any method to determine the window ID of the original window (the opener) from the perspective of the ne ...

Error: jQuery is unable to access the property 'xxx' because it is undefined

While attempting to make a post request from the site to the server with user input data, I encountered an error message saying TypeError: Cannot read property 'vehicle' of undefined as the response. Here is the HTML and script data: <!DOCTY ...

Tips for retrieving the user-input value from an HTML text field

Exploring the world of JS, I set out to create a basic calculator after just one week of lessons. However, I hit a roadblock when trying to extract user-input values from my HTML text fields. Here's a snippet of my html: <div class="conta ...

Issues with nested array filtering in JS/Angular causing unexpected outcomes

I am faced with a particular scenario where I need to make three HTTP requests to a REST API. Once the data is loaded, I have to perform post-processing on the client side. Here's what I have: An array of "brands" An array of "materials" An array o ...

Tips for sending props to Material UI components

Hey there! I'm currently working on a progressbar component that utilizes animations to animate the progress. I've styled the component using Material UI classes and integrated it into another component where I pass props to customize the progres ...

Inquiry about Date and Time Selection Tool

I am working on a PHP project that includes two textboxes: one for selecting dates and the other for choosing a specific time. What I need assistance with is disabling any times before the selected date in the second timepicker textbox if today's dat ...

Personalize the file button for uploading images

I have a button to upload image files and I want to customize it to allow for uploading more than one image file. What is the logic to achieve this? <input type="file" />, which renders a choose button with text that says `no files chosen` in the sa ...

jquery method for retrieving default value from dropdown list

When no option is selected from the dropdown list, I require the default value to be used for business logic purposes. ...

The click event will not be triggered if the element is removed by my blur event

My dropdown list is dynamic, with clickable items that trigger actions when clicked. Upon focus, the list displays suggested items When blurred, the list clears its contents The issue arises when blur/focusout events are triggered, causing my element to ...

Angular's ng-repeat allows you to iterate over a collection and

I have 4 different product categories that I want to display in 3 separate sections using AngularJS. Is there a way to repeat ng-repeat based on the product category? Take a look at my plnkr: http://plnkr.co/edit/XdB2tv03RvYLrUsXFRbw?p=preview var produc ...

Issue: The key length and initialization vector length are incorrect when using the AES-256-CBC encryption algorithm

Within my coding project, I have developed two essential functions that utilize the AES-256-CBC encryption and decryption algorithm: import * as crypto from "crypto"; export const encrypt = (text: string, key: string, iv: string) => { con ...

Guide to invoking a jQuery function by clicking on each link tab

Below is a snippet of jQuery code that I am working with: <script> var init = function() { // Resize the canvases) for (i = 1; i <= 9; i++) { var s = "snowfall" + i var canvas = document.getElementById( ...

What is the significance of incorporating 'Actions' as data within the Redux framework?

According to Redux documentation, creating actions and action creators is necessary. Here's an example: function addTodo(filter) { return { type: SET_VISIBILITY_FILTER, filter } } Next step is to write reducers, like this: function t ...

Can halting an ajax function mid-process prevent it from finishing?

My objective is to convert a video using ffmpeg, which tends to take a considerable amount of time to complete. I'm considering sending an ajax request to the server for this task, but I don't want the user to have to wait until the video convers ...