Search code examples
javascripthtmljqueryajaxbootstrap-modal

Bootstrap Modal Not closing after successful Ajax Call


I am getting success in the Ajax Call but after submission, it is not hiding.

I tried .hide(); .modal('hide');

Here is

    <div class="modal fade" id="addWorkModal" tabindex="-1" role="dialog" aria-labelledby="addWorkModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addWorkModalLabel">Add Work</h5>
                </div>
                <div class="modal-body">
                    <form id="create-work-form">
                        {% csrf_token %}
                        {{ work_form|crispy }}
                        <div class="form-group">
                            <label for="user-id">User ID:</label>
                            <input type="text" class="form-control" id="user-id" name="user" value="{{ client.user.id }}">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="save-work-button">Save Work</button>
                </div>
            </div>
        </div>
    </div>
<script>
document.getElementById('save-work-button').addEventListener('click', function() {
    var form = document.getElementById('create-work-form');
    var formData = new FormData(form);

    var url = "";
    console.log('URL being requested:', url);

    $.ajax({
        url: url,
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            console.log("AJAX call successful"); // Debugging
            if (response.work) {
                $('#addWorkModal').modal('hide');
            } else {
                // Handle errors from response
                var errorText = 'Error creating work: ' + JSON.stringify(response.errors || 'Unknown error');
                console.error(errorText);  // Log error to the console instead of alerting
            }
        },
        error: function(xhr, status, error) {
            var errorMsg = 'An error occurred. Status: ' + status + '. Error: ' + error;
            if(xhr.responseText) {
                errorMsg += '. Response: ' + xhr.responseText;
            }
            console.error(errorMsg);  // Log error to the console instead of alerting
        }
    });
});

My question after submitting the form how can I close or hide the modal automatically as it is not suppose to appear after submission.


Solution

  • Try to replace this:

    $('#addWorkModal').modal('hide');
    

    with this:

    document.getElementById('addWorkModal').style.display = 'none';
    

    and tell me if it helped.

    EDIT:

    If the modal is not hiding as expected, there are a few things you can check:

    1. Ensure jQuery is Loaded:

    Make sure that jQuery is loaded before this script. You can include it in your HTML file before the script:

    <!-- Include jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <!-- Your script here -->
    <script>
        // Your script goes here
    </script>

    1. Check the Response:

    Add a console.log(response) in your success callback to see what the server is returning. Make sure that the response is as expected and that the code inside the if (response.work) block is being executed.

    1. Check for JavaScript Errors:

    Open the browser console (usually F12 or right-click and "Inspect" then go to the "Console" tab) to check for any JavaScript errors. This might give you more information about what's going wrong.

    1. Check Modal Element Existence:

    Ensure that the modal element with the ID addWorkModal actually exists in the DOM. If it doesn't, jQuery won't find it, and the modal('hide') won't work.

    2nd EDIT:

    Create a CSS element .hideModal, like so:

    .hideModal{display: none!important}
    

    And then call it with the following JavaScript:

    var element = document.getElementById("addWorkModal");
    element.classList.add("hideModal");