Launch a Bootstrap modal window using Spring MVC backend

I am working with a Spring MVC controller and a bootstrap page.

My goal is to display a confirmation window when submitting a form and sending some payload to a specific endpoint if certain conditions are not met:

API:

@PostMapping(value = "/pairs")
public String addPair(@ModelAttribute StepForm addPairStepForm,
                      Model model) {
....... // perform checks and trigger modal dialog in front end
}

Bootstrap page:

<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>test</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<main>
        
    <!-- Modal -->
    <div class="modal fade" id="validationModal" tabindex="-1" aria-labelledby="validationModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="validationModalLabel">Confirmation</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    Pair already exists for the same exchange.
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary">Continue</button>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
                   
        <div class="row justify-content-center align-items-center">
            <div class="col-md-10">
                <form id="add_pair_form" class="form-inline" action="#" th:action="@{/pairs}"
                      th:object="${stepForm}"
                      autocomplete="off"
                      method="post">

                    <div class="row g-3 align-items-center mb-1 mt-1">
                        <div class="col-auto">
                            <label for="pair" class="form-label">New</label>
                        </div>
                        <div class="col-auto">
                            <input id="pair" class="form-control" name="pair" type="text"
                                   placeholder="Pair to be added."
                                   th:field="*{pair}"
                                   required
                                   autofocus>
                        ......................................
                        </div>                            
                    </div>

                    <div class="form-group mb-1 mt-1">
                    <button type="submit" class="btn btn-primary submit_btn">Submit</button>

                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#validationModal">
                        Validate
                    </button>
                </div>
                    
                </form>

            </div>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
            crossorigin="anonymous"></script>       
</main>
</body>
</html>

I am looking for a way to trigger the modal dialog window upon form submission and response from the Spring backend. The aim is to conduct validation on the backend and if an error occurs, display the dialog window.

Answer №1

To initiate the display of your modal, you require a signaling mechanism within your view.

Utilizing Spring and Thymeleaf, one approach is to set a boolean flag, such as

pairAlreadyExistsWithTheSameExchange
, in your Spring model within the addPairs method when certain conditions are met:

@PostMapping(value = "/pairs")
public String addPair(@ModelAttribute StepForm addPairStepForm,
                      Model model) {
  ....... // perform checks and trigger modal dialog on the frontend
  
  // set flag if necessary
  model.addAttribute("pairAlreadyExistsWithTheSameExchange", true);

  // ...
  return "path to your thymeleaf page";
}

Next, update your view to acknowledge this new model attribute and show the modal accordingly.

For instance, include the modal in a way that makes it visible by adding the show class and setting display: block if

pairAlreadyExistsWithTheSameExchange
is true:

<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>test</title>
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9cbc6c6ddcad8cdbfcbaac7ceccfbcfe"/>
</body>

Alternatively, keep the modal structure from your original code and inject a JavaScript snippet like the following into your HTML:

<script type="text/javascript" th:if="${pairAlreadyExistsWithTheSameExchange}">
    var validationModal = new bootstrap.Modal(document.getElementById('validationModal'));
    validationModal.show();
</script>

This approach allows for a clear and straightforward implementation compared to other methods such as using request parameters.

Answer №2

For instance, let's say you need to verify the input with id="pair". Your objective is to determine if this input field is either empty or not:

$( "#add_pair_form" ).submit(function( event ) {
  event.preventDefault();
  const pairValue = $("#pain").val();

  if(pairValue.trim() == "") {
     // display alert dialogue
    alert('YOUR ERROR MESSAGE');
    return;
  }
  ...

  $.ajax({
    url: "API_URL",
    success: function(result){
      // result holds the data from response
      ....
    }
  });
});

Remember, this was just an illustration :)

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

A tutorial on how to switch out a font-awesome icon simply by clicking on it - collapsible content

I have some HTML code with a script for my website that allows text to be collapsed or expanded by clicking on a font awesome arrow. I am looking to have an arrow that points up when clicked to collapse the text and points down when clicked to expand the t ...

What is the best way to incorporate my light/dark mode theme into index.js and have my header serve as the switch location?

Could someone assist me with setting up a theme around my index.js components and using a switch state in my header.js to toggle between light and dark themes? I'm looking for a way to simplify the process to minimize the amount of code needed. As a ...

Error with Ajax-bound selection (dropdown) - possibly due to an empty list in certain browsers

Upon taking over a project involving ASP.Net AJAX and JSON, I encountered an issue on a page that loads a large select (combo box) list of 1,430 entries. This list loads successfully on our main search page but produces an error in MicrosoftAjaxTemplates.d ...

Create an onClick function that can direct you to a specific hyperlink without triggering a new browser window to open

Material UI is being used and a home icon has been imported into the navbar as shown below <Home edge="start" color="inherit" aria-label="home" onClick={event => window.location.href='/ <Home fontSize="lar ...

Switching from HTML to BBCode during the editing process

My issue lies in converting BBCode to HTML and then editing the code on a page with AJAX. When editing in a <textarea>, the HTML tags show up instead of the original BBCode. For instance, if I submit [b]bold text[/b] and save it to my database, the ...

Is there a way to always keep an element positioned directly above a fluid image that is perfectly centered?

My current project involves creating an overlay to display a fluid image of any size. The challenge I'm facing is how to consistently position the close button 30px above the image and flush with its right edge. The catch is that the container doesn&a ...

Acquire the HTML code, make substitutions, and save it as a string variable without altering the DOM element

I have a DOM element that looks like this: <div class="list-item"> <div class="name"></div> <div class="id" data-id=""></div> <a href="">Link</a> </div> ...

Exploring the possibilities with Node.js and OpenCV

I'm experiencing difficulties with face tracking and detection using the npm opencv package. Right now, I'm attempting to draw a circle around each detected face. Below are the error details and associated files. I'm unsure if it's a b ...

What could be causing my Javascript prompts to not appear in my Express.IO .ejs file?

I am fairly new to JavaScript and exploring Node with Express.IO. I'm currently working on a project that involves tracking real-time connections made by different 'users' to the server. However, I've encountered an issue where my promp ...

Link the Sass variable to Vue props

When working on creating reusable components in Vue.js, I often utilize Sass variables for maintaining consistency in colors, sizes, and other styles. However, I recently encountered an issue with passing Sass variables using props in Vue.js. If I directly ...

Is it possible to combine several m3u8 files into a single m3u8 file?

I am looking to consolidate multiple m3u8 files into a single file for seamless playback in one video player. How can I achieve this without compromising the individual clips? For instance, if I have zebra.m3u8, giraffe.m3u8, and lion.m3u8 files, is it pos ...

ng-required is ineffective when used with number inputs that have a minimum value requirement

In my form, I have implemented a checkbox that, when checked, toggles the visibility of a div using AngularJS's ng-show. Within this div, there is an input field of type "number" with a validation setting of min="10000". I am trying to prevent the f ...

Filtering JSON data by the keys of a Backbone.js model

I have a standard backbone collection that I am working with. (function($){ var DataModel = Backbone.Model.extend({}); var DataCollection = Backbone.Collection.extend({ model: DataModel, url: 'assets/path_data.json' }); var data ...

A guide to performing a LEFT JOIN on two JSON data sources from external URLs

I've been attempting to achieve the following outcome using external JSON data but haven't had any luck finding a solution on search engines or forums. Can anyone provide assistance with this? Thank you in advance. people = [{id: 1, name: "Tom" ...

Capturing user-selected option from dropdown menu using npm

I am a beginner when it comes to node.js and async programming. My current project involves creating a program that shuffles a Spotify playlist. I have managed to store the user's playlists in an array for easier access. My goal is to present this ar ...

Creating multiple div elements with changing content dynamically

I am facing an issue with a div named 'red' on my website where user messages overflow the 40px length of the div. To prevent this, I want to duplicate the 'red' div every time a message is sent so that the messages stay within the boun ...

What is the reason for the malfunctioning of this button upon clicking?

Attempting to customize my personal website by making the sidebar width change when the sidebar button is clicked. I'm puzzled as to why it's not working as intended. I prefer to figure it out independently but any helpful tips would be appreciat ...

Experimenting with AngularJS 1.6 class-oriented controllers through the lens of Jasmine/Karma testing

Struggling to use jasmine/karma to test my class-based controllers, unfortunately without any success. Most examples I come across are dated back to 2014 or older. I've made sure to load the angular and angular-mock files in my karma configuration fil ...

Building a Spring Boot/Angular application that routes using an independent HTML file

I have an interesting request - I am looking to create a standalone HTML file that is not associated with my angular or spring boot app in any way. Currently: 'localhost:8080/' --- (redirects to angular app at '/#!/login') What I wa ...

Unable to resolve 500 error on Vercel in Next.js despite successful local development

Here is the content of route.ts import fs from 'fs'; import path from 'path'; import PizZip from 'pizzip'; import Docxtemplater from 'docxtemplater'; import { NextRequest, NextResponse } from 'next/server'; ...