Utilize Ajax to prevent the display of additional modals when encountering errors in the form data

I have a multi-step form on my website that consists of several modals. Each time I click "next," it triggers the next modal and submits form data. I am currently working on implementing validation for these modals, where I want to prevent the activation of the next modal if there is missing data or reload the current modal in case of an error. Despite showing that an error exists in my ajax call, using

$('#Modal_2_Toggle').modal('show');
to reload the specific modal with the error allows the user to proceed to the next modal. I need assistance in blocking the loading of the next modal until data.error is false. Below is the HTML code for the modal in question:

<div class="modal fade" id="Modal_2_Toggle" aria-hidden="true" aria-labelledby="Modal_2_ToggleLabel" tabindex="-1">
                  <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                      <div class="modal-header">
                        <h5 class="modal-title" id="Modal_2_ToggleLabel">Question 2</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                      </div>
                      <div class="modal-body">
                        <div class="progress">
                          <div class="progress-bar" role="progressbar" style="width: 18%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">18%</div>
                        </div>                        
                        <form method="POST" enctype="multipart/form-data", id="form_2">
                            {{ form_2.csrf_token }}
                            <p>
                              <br>
                                {{ form_2.consumption.label(class="form-label") }}
                                {{ form_2.consumption(class="form-control form-control-sm", id="consumptionInput") }}
                            </p>
                            {{ form_2.submit(class="btn btn-primary", id="form_2_submit", hidden="true") }}
                            <br>
                        </form>
                        <div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
                      </div>
                      <div class="modal-footer">
                        <button class="btn btn-primary modal_btn" data-bs-target="#Modal_1_Toggle" data-bs-toggle="modal" data-bs-dismiss="modal">Previous</button>
                        <button class="btn btn-primary modal_btn" data-bs-target="#Modal_3_Toggle" data-bs-toggle="modal" data-bs-dismiss="modal" form="form_2" id="modal_2_confirm">Next</button>
                      </div>
                    </div>
                  </div>
                </div>

Here is my JavaScript code:

$(document).ready(function() {

    $('#form_2').on('submit', function(event) {

        $.ajax({
            data : {
                consumption : $('#consumptionInput').val(),
            },
            type : 'POST',
            url : '/test'
        })
        .done(function(data){
            if (data.error) {
                $('#errorAlert').text(data.error).show();
                $('#Modal_2_Toggle').modal('show'); <- I ASSUMED THIS WOULD RELOAD THE MODAL
            }
        });
        
        event.preventDefault();
        
    });

});

Answer №1

Perhaps your current approach to using a multi-step form may not be the most suitable for your requirements.
Consider exploring one of the modern JavaScript frameworks like Angular, React, Vue, or Svelte, which could potentially assist you in achieving your goal more efficiently and effectively.

However, the example provided below demonstrates a solution that utilizes a single modal dialog with integrated slides. This design allows for step-by-step progression, ensuring that each step must be completed correctly before advancing to the next. The behavior is dictated by error codes received from the server.

<!DOCTYPE html>
<html>
  <head>
    // Meta tags
    // Link to Bootstrap CSS
    </head>
  <body>

    <!-- Button to trigger modal -->
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
      Launch demo modal
    </button>

    <!-- Modal dialog -->
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
            // Close button
          </div>

            <form
              // Form 1 details
            >
              {{ form1.csrf_token }}
              <div class="modal-body">
                // Form inputs
              </div>
              <div class="modal-footer">
                // Buttons
              </div>
            </form>            

            <form
              // Form 2 details
            >
              // Form fields
            </form>

            <form
              // Form 3 details             
            >
              // Fields and buttons
            </form>
        </div>
      </div>
    </div>

    // Script tags
  </body>
</html>
from flask import (
    Flask,
    render_template,
    request
);
// Python script
// Form classes 
// Routes and functions for handling form data 

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

Is there a way to display multiple Bootstrap 5 modals simultaneously without automatically closing the previous ones?

My current project utilizes bootstrap 5.2, which is a departure from the previous version, bootstrap 3. In bootstrap 3, it was possible to open multiple modals on top of each other, creating an overlapping effect. However, in bootstrap 5 and 5.2, the behav ...

Iterate through each selection from the multiple chosen in Select2, and utilize jQuery to add the text value of the

When I click a button, I want to add the selected item(s) to a div #list <select class="select2" multiple="multiple" name="string_items[]" id="string_items"> <option>value I want to add</option> </select> Transition from this: ...

execute function following ng-repeat

I'm diving into Angular for the first time and I want to start with a simple example. After using ng-repeat to display some data, I'd like to manipulate that data with JavaScript functions. However, I'm not sure when to trigger the JavaScri ...

When a key is pressed, apply a background color and fade out effect using JavaScript

Whenever the enter key is pressed, I want to make a red color appear briefly and then fade out quickly to create a blinking effect. I attempted adding a new class on Keypress that would transition the opacity to 0: function enterpressalert(e, text) { ...

including identical item in the array

<!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css"> <body> <script> var app = angul ...

I'm currently facing difficulties trying to implement AJAX with JavaScript and PHP as the desired output is not being

My query is quite straightforward - why isn't the code functioning properly? I am attempting to have the text echoed in PHP displayed inside a div with the ID of "show". Interestingly, this works with a txt file but not with PHP or any other type of f ...

What is the best way to retrieve user data and format the output using JavaScript into a structured form?

I am trying to achieve the functionality shown in this image: https://i.sstatic.net/svzvc.png My goal is to extract user input from a form and display it on my webpage using JavaScript. Below is the code snippet that I have been working on. Code: f ...

The Socket.IO connection appears to be established successfully when the code is executed from the Node REPL

When running the code from a file, the client fails to connect to the server but successfully connects when executed from the repl. Below is the server-side code: const http = require("http"); const express = require("express"); const socketIO = require( ...

Ways to repair a website iframe malfunction

Whenever I visit this specific URL : (note: using an Ad-blocker is recommended) The link to the webpage loads properly, with no issues. However, attempting to load the same page through an iframe in my HTML code triggers an error: Here is my HTML code : ...

Employing Visual Composer within WordPress has resulted in the raw JavaScript not being properly applied to my raw HTML code

Sharing some code that functions properly in my browser and I want to implement on my WordPress page: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8> <!-- Getting jQuery --> <script src="http://ajax.goog ...

What steps can I take to improve my routing structure in nodejs and express?

My current WebAPI code is pretty modular, but I want to make it even more so. Right now, all the routes are in my server.js file and I would like to separate them into individual controllers. Any suggestions on how to achieve that? Here's an example: ...

Deleting a row from the table with a single click on the X icon

Is there a way to delete individual rows in a table by clicking on a close icon instead of removing all rows at once? Additionally, I am looking for a better method to display rows in a table. You can view my current implementation here: link -> jsfiddl ...

React.js application experiencing a lack of response from EventSource on-message function

Currently, I am in the process of migrating an established production application from jquery to react.js. The backend is built using Java (spring boot) and the existing app utilizes Server-Sent Events to push specific types of notifications from the serve ...

Manipulate component properties using CSS hover in React with Material-UI

I am attempting to modify the noWrap property of a Typography element when hovering over it. I have defined a custom CSS class for the parent element and the hover functionality is working correctly. However, I am unsure how to adjust the noWrap property u ...

Can you customize the first element within a span tag using a for loop?

I am having an issue where only the last element in a span is being set within a for loop. The code is functioning correctly, but I want to ensure that the first element is the one set as cust_name. success : function(data) { co ...

How come my variable doesn't show up in the view even though I filled it in the controller?

I'm having trouble with my AngularJS setup. The angular.min.js file is located in the js folder, following a code example from O'Reilly's book. However, for some reason it is not working on my computer. //controller.js function HelloCont ...

transform a JSON object into a targeted JSON array

Looking to transform a JSON object into an array format, like so: [ { "name": "Batting" ,"data": [10,20,30,40]} , { "name": "Bowling" ,"data": [10,30,50,70] },{ "name": "Fielding" ,"data": [20,40,50,70]}] While I can create JSON objects for each index, I ...

Can we gather all elements with the 'required' attribute and assign them to a single event in JavaScript?

I am facing an issue with a button that triggers a function when clicked. The problem is that even though the required fields are not filled, the function still gets executed. This is how I have set it up: $('#SubmitButton').click(function() { ...

Exploring Iconography in Amcharts

Is there a simple way to include images/icons within a chart using x and y coordinates? I'm new to javascript and amcharts (am4charts) so any assistance would be greatly appreciated! I've searched for solutions on stackoverflow, like this one o ...

Troubleshooting: Wordpress Ajax call failing with 500 Internal Server Error

Dealing with Ajax calls in a custom page template on Wordpress can be more complex than expected. I've struggled to get it running smoothly without crashing my entire site. It's puzzling why this particular approach is necessary when other Ajax c ...