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

Implementing Canvas Offset in a jQuery Mobile Environment

I have positioned a pen ready for use at this location. http://codepen.io/prantikv/pen/LEbRKY Currently, I am utilizing a canvas to track mouse movements or touch input. It performs as expected when jQuery or jQuery mobile is not included. However, upon ...

Ways to eliminate unnecessary items from a JavaScript object array and generate a fresh array

My JavaScript object array contains the following attributes: [ { active: true conditionText: "Really try not to die. We cannot afford to lose people" conditionType: "CONDITION" id: 12 identifier: "A1" ...

Using jQuery to animate a form submission in CodeIgniter

I have integrated two jQuery plugins into my application, which are: jQuery validate : . jQuery blockui : http://malsup.com/jquery/block/#download The application is developed using PHP Codeigniter and jQuery. It consists of a form created with the fol ...

Processing one file to submit two forms to the database in Express

I am facing an issue with two forms on one form.hbs page using the same process.js file. Each form is processed by a different submit button for separate occasions. The first submit button works correctly, processing the data in the process.js file and se ...

Tips for setting a value from an AJAX-created element into a concealed form field

There is a div that contains a button. When the button is clicked, a form appears. The div's id is then assigned to a hidden field within the form. This functionality works for the divs that are present on the page when it initially loads, but it does ...

When the month picker is selected, my intention is to retrieve the true value. However, I am encountering an issue where it consistently returns the false value instead

I created a month picker similar to the image provided. After removing unnecessary code, I was left with only the part that generates questions. Initially, when the month picker renders, no value is selected. However, upon selecting a month, the value is d ...

How can I apply a jquery method to a variable when JavaScript already has a method with the same name?

Is it possible to call the .which function on a character without needing to differentiate between browser types by using the jQuery .which method, which supposedly normalizes for browser discrepancies? I know that the inherent javascript method is also ...

Issue with printing error messages for JavaScript form validation

I have implemented the following code for a form to handle validation and display errors below the fields when they occur: <!DOCTYPE html> <html> <head> <style type="text/css"> .errorcss { background-color: yellow; color:re ...

What methods should I use to modify the upcoming array of objects?

I have been struggling with this exercise for about an hour now, and I can't figure it out. Can someone please help me with this? Here is the array that I retrieved from the database: View Base Array Image let data = [ { "name": "October : 2019", "u ...

Navigating through tables and selecting rows

I am currently facing an issue with my HTML table that consists of 1000 rows and 26 columns. To navigate between rows and make selections, I have implemented a jQuery plugin on the table. The problem lies in the performance of the plugin, even with the la ...

Angular 2 event emitter falling behind schedule

I am currently utilizing Angular 2 beta 6. The custom event I created is not being captured import {Component, OnInit, EventEmitter} from 'angular2/core'; import {NgForm} from 'angular2/common'; import {Output} from "angular2/core" ...

What steps should I take to ensure that the login page functions properly?

Below is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login Pag ...

Creating a React component that allows for pagination using data fetched from a

I have a Spring Boot endpoint that retrieves and lists items from a database: @RequestMapping(method = RequestMethod.GET, value = "/task", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> processTask(@Valid TaskSearchP ...

When trying to connect to the MongoDB database using Node.js and Express, the content

Currently immersing myself in the world of MongoDB for Node.js Here is my app.js: var express = require('express'), app = express(), engines = require('consolidate'), MongoClient = require('mongodb').MongoClient, as ...

Using knockout to data bind a function to an onclick event that takes in multiple parameters

I've scoured the internet and experimented with various methods, but I'm encountering an issue where the click function intermittently fails to fire. Below is my HTML code snippet: <input type="radio" data-bind="checked:a, checkedValue: 0 ...

Creating a custom arrow design for a select input field using CSS

I'm currently developing a website (using Wordpress with a custom theme) and I want to incorporate an up/down arrow in the select input field using CSS. The HTML code I have for creating the up/down arrow in the select input field is as follows: < ...

Do we really need to use redux reducer cases?

Is it really necessary to have reducers in every case, or can actions and effects (ngrx) handle everything instead? For instance, I only have a load and load-success action in my code. I use the 'load' action just for displaying a loading spinne ...

The performance of dom-repeat may be impacted when dealing with sizable objects, such as those containing base64 encoded images

Currently, I am encountering an issue while generating a dom-repeat using a list of objects. Each object in the list has an imgUrl key containing a large base64 encoded image. However, when I generate the dom-repeat in this manner, each item appears undef ...

Submitting a form through Ajax is resulting in multiple submissions

Whenever I use Ajax to submit this form, it ends up posting multiple times without any obvious reason. Sometimes, it posts the form up to 10 times even though the submit button is clicked only once. I'm puzzled as to why this behavior is happening. An ...

What steps can I take to make sure JSON keys containing only digits are treated as Strings instead of Numbers?

Within a JSON String, I have IDs as keys, represented as Strings of numbers, while the values are actual Numbers (Float). The problem arises when parsing this information to obtain an object in Safari 10.1.2... var jsonData = "{\"53352\":0.6, ...