Enhancing Stock Information with AJAX and Java

I'm currently developing a stock trading application that relies on Yahoo Finance to retrieve stock prices.

My goal is to have the prices automatically update every 5 seconds without needing to refresh the page. I understand that this can be achieved using AJAX technology.

This is what my Java controller looks like:

@GetMapping("/banking/stocks")
public String stocks(Model model) {

model.addAttribute("stock", new StockDto());
try {
    List<Stock> stocks = stockService.getDefaultStocks(getCurrentUser());
    model.addAttribute("stocks", stocks);

} catch (IOException e) {
    e.printStackTrace();
}
return "stocks.html";
}

Here's how the HTML is structured:

<tbody>
<tr th:each="stock : ${stocks}">
    <td th:text="'$'+${stock.getSymbol()}"></td>                                                    
    <td th:text="${stock.getName()}"></td>
    <td th:text="${stock.getQuote().getPrice()}"></td>
    <td
        th:class="${stock.getQuote().getChangeInPercent() > 0 ? 'text-success' : 'text-danger'}"
        th:text="${stock.getQuote().getChangeInPercent() + '%'}"></td>
    <td th:if="${stock.getDividend().getAnnualYield() != null}"
        th:text="${stock.getDividend().getAnnualYield() + '%'}">0.00%</td>
    <td th:if="${stock.getDividend().getAnnualYield() == null}">0.00%</td>
</tr>

I am struggling with implementing AJAX to ensure getPrice() is called and updated every 5 seconds on the page. Would greatly appreciate any help or guidance on this issue.

Thank you!

Answer №1

Thmyleaf functions as a template engine, meaning it sets values after the page has loaded. For dynamic pricing, it's best to utilize JavaScript to swap out HTML content instead of relying on Thymeleaf.

Check out this straightforward demonstration:

[Codepen](https://codepen.io/chawol/pen/oNzaXdg)

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 escaping single quotes in JSON.stringify when using a replacer function

I'm attempting to replace single quotation marks in the values of my JSON string with \' however, it seems to not be working when I try to use the replacer function. var myObj = { test: "'p'" } var re ...

Fullcalendar making multiple AJAX calls without refreshing the page

Each time I click on a day in the month view, a modal will appear. Within that modal, there is a button to add a new event. Clicking on it will trigger another modal for the Add Event form. The issue arises when I open and close the first modal frequentl ...

Accessing properties in JavaScript using square brackets

When I input the following code into my Chrome console: var object = {0:0, 1:1} I am able to retrieve the values by calling object[0] and object[1]. Surprisingly, even when I use object["0"] and object["1"], I still get the same results. Then, if I redef ...

Checkbox selection not retained after update panel triggers

I am facing an issue with a div, id = campaignDiv, which loads its content dynamically. The content consists of checkboxes. There is an update panel that triggers every 30 seconds. The Challenge Whenever the update panel triggers, the checkboxes reset ...

Above the search box in jQuery Datatable's search box, there is search text displayed

My datatable looks like this: var exTable1 = $("#exTable").DataTable({ "language": { "search": "Filter", "searchPlaceholder": "search", "loadingRecords": "", }, data: datasrc "dom": '<"top"lf>rt<"botto ...

Exploring the possibilities of incorporating animation in model-viewer using a-frame examples

I am currently working on a project where I am looking to repurpose the following example: All I need to do is add a trigger that will start the animation on a click event. I have successfully set this up to run on my server by using the code from https: ...

Tips for disregarding global CSS in Nuxt.js?

I've been utilizing a boilerplate that integrates with the CoreUI template from GitHub, and it's been working well. However, I am now looking to customize my index page with a unique style, and I'm encountering issues where the global CSS fr ...

Show two choices in a select box next to each other

I've been attempting to display a select box with two options side by side in a list format. Struggling to find any libraries that can achieve this functionality. Here is an example: <select> <option x><option y> <optio ...

My Javascript file is not being recognized by MVC

Initially, I created an MVC application without fully understanding that MVC is more backend-oriented than frontend-focused. I ended up building a simple website with just HTML, CSS, and Javascript files, which worked perfectly. However, when I tried to in ...

Is there a way to arrange strings in the proper alphabetical sequence solely by using if statements in my code?

Is there a way for me to organize three string values alphabetically using only if statements? I've realized that the operators I'm using are typically used for integer values, not strings. What other operator can I use that would work for strin ...

Using Javascript to transmit audio via a microphone

I am currently trying to use Selenium to simulate a user on a website that features audio chat. My goal is to emulate the user speaking through the microphone. While I have come across several resources discussing how to listen to the microphone in JavaSc ...

Send back the outcome in object form

I'm having trouble retrieving the value of this object. I attempted to use json.count(id_reported) and json['count(id_reported)'], but neither worked successfully. const json = { 'count(id_reported)': 21 }; //console.lo ...

Need to implement a parallel directives controller without the need to create a parent controller

Query: Can a direct connection be established between two parallel directives without the need for a factory, parent-directive, or emit/broadcast, but simply using require: 'directiveA'? Disclaimer: If this request seems far-fetched, please let ...

Uploading Files in HTML

My goal is to create a way to input a file using the following method: Input file: <input type="file" name="-f" id="fa"> I would like to include an HTML link (upload example) that, when clicked, will upload an example file without opening the file ...

Conceal every concealed mongoose processes and attributes

In my Nuxt 3 project, I currently have this server-side code snippet: findAuthorByEmail(email: string, showPassword = false) { return Author.findOne({ email }) .select(showPassword ? "" : "-password_hash") .lean(); } ...

Experiencing some unusual shadows in my Three.js project while attempting to add a simple shadow effect to a cube or group of cubes

Trying my hand at implementing shadows in Three.js, even though I am fairly new to JavaScript. My attempts to create a cube with a proper shadow have yielded partial results, as only a portion of the mesh seems to be casting the shadow. https://i.sstatic. ...

Extracting JSON data within ajax's success callback

I am currently working on parsing and displaying JSON data that is returned from a server. To accomplish this, I have set up an AJAX call that reads user input, sends it to a PHP page via POST method, and the PHP page var_dumps the array containing the JSO ...

Tips for importing modules for unit tests using QUnit

Lately, I've been working on implementing unit tests for some of my modular ES6 code. The project structure I have looks something like this: project └───src | └───js | cumsum.js | index.js <--- main file └─� ...

Fixing Sticky Navigation Bar on Scroll (JavaScript, HTML, CSS)

I'm working on this site as a fun side project, but I've hit a roadblock. The sticky nav bar I implemented jumps when the user scrolls down far enough. Despite reading through other discussions, I can't seem to figure out the solution. I su ...

After removing the div element, the error message 'Cannot read property 'offsetWidth' of undefined or null reference' is displayed

Currently, I am encountering an error on my website stating "Cannot read property 'offsetWidth' of undefined or null reference" after commenting out 2 divs in a bootstrap carousel. The carousel was created by someone who is not available to me at ...