Search code examples
javascriptjavaspring-bootthymeleafalert

How do I conditionally call an alert() in JavaScript based on conditions from my Java code?


I am trying to display an alert (a "Congratulations!" message) if data is recorded (through a form on the web page) that meets or exceeds a set Goal (that has already been recorded and stored); I was also considering maybe conditionally playing a cute little sound to go with it, but I would like to get the pop-up working first of course. I am pretty novice with JavaScript, so I hope this issue isn't a stupid oversight on my part. I did do some digging online and couldn't quite find a solution to fit exactly what I am trying to do here.

So, in my Java code I check if the data being recorded meets or exceeds the goal, and if it does then a boolean variable in the Goal object is set to true (to reflect that the Goal was completed). That boolean variable is being updated correctly. However, in my web page I cannot get the alert to pop up when wrapped in the conditions I have it in.

I know for a fact that the line of Java code below is being seen because I put a print statement before and after it, and both are printing.

Here is the related Java code:

model.addAttribute("goalMet", true);

And here is the related HTML and JS (I am using Thymeleaf):

<div th:if="${goalMet}">
<p> abc123 </p>
<script th:inline="javascript">
    function congratulate() {
      alert("Congratulations on achieving your Goal!");
    }
    congratulate()
</script>
</div>

The abc123 was just thrown in there for debugging, and it currently does not show up after recording data that meets a goal. I have tried a few variations of the script tag, both with and without the th:inline="javascript" part. I also tried moving the function definition into the html head tags and just calling congratulate() in this conditional block. All of my attempts so far have been unsuccessful.

The only effects I am seeing after recording data that meets a goal is that the URL gets "?goalMet=true" appended to it.


Solution

  • Thanks to Randy Casburn's suggestions, I was able to get this working using Redirect Attributes. Here is what I did:

    Changed

    model.addAttribute("goalMet", true);
    

    To

    redirectAttrs.addFlashAttribute("goalMet", true);
    

    And I added

    "RedirectAttributes redirectAttrs" as a parameter to the method that does the redirect.