'Control JavaScript window open and close

I have a modal window that allows me to create new instances but I'm getting some strange behaviour:

  • If I get an error because the site already exists the window closes
  • If I manage to insert the new site the window stays open

I need to reverse the behaviour.

const addBtn = document.getElementById('add-btn')
const modalBody = document.getElementById('model-body')
const siteForm = document.getElementById('site-form')
const alertBox = document.getElementById('alert-box')

const siteName = document.getElementById('id_name')
const siteCity = document.getElementById('id_city')
const csrf = document.getElementsByName('csrfmiddlewaretoken')[0].value

const handleAlerts = (type, msg) => {
    alertBox.innerHTML = `
        <div class="alert alert-${type}" role="alert">
            ${msg}
        </div>
    `
}


addBtn.addEventListener('click', ()=>{
       
    siteForm.addEventListener('submit', e=>{
        if (siteName.value ===''){
            handleAlerts('danger', 'Name field cannot be left empty')
            siteName.focus()
        }else{ 
            e.preventDefault()
            const formData = new FormData()
            formData.append('csrfmiddlewaretoken', csrf)
            formData.append('name', siteName.value)
            formData.append('city', siteCity.value)

            $.ajax({
                type: 'POST',
                url: '/savesite/',
                data: formData,
                success: function(response){                
                    handleAlerts('success', 'Site added')
                    siteForm.reset()
                    window.close();
                },
                error: function(error){
                    console.log(error)
                    handleAlerts('danger', 'Site already exists in that city')
                },
                processData: false,
                contentType: false,
            })            
        }
    })    
})

After changing the above code I now get the message at the console: Scripts may close only windows that were opened by them.

This is the HTML file that opens the modal window:

{% extends 'base.html' %}
{% load static %}
{% load crispy_forms_tags %}

{% block scripts %}
    <script src="{% static 'objects/home.js' %}" defer></script>
{% endblock scripts %}


{% block title %}
Site List
{% endblock title %}


{% block content %}

<!-- Modal -->
<div class="modal fade" id="addModal" 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">Add Site</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body" id="modal-body">
            <div id="alert-box"></div>
            <form id="site-form">
                {% csrf_token %}
                {{site_form|crispy}}
                <button type="submit" class="btn btn-info mt-3">Save</button>
            </form>
        </div>
      </div>
    </div>
  </div>


  <h1>Site List</h1>
<hr>

<button type="submit" class="btn btn-danger mb-5" id="add-btn" data-bs-toggle="modal" data-bs-target="#addModal">Add new Site</button>

{% for obj in object_list %}
    <div class="card mb-3">
        <div class="card-body">
            <h5 class="card-title">{{obj.name}}</h5>
            <p class="card-text">{{obj.city}}</p>
            <a href="{{obj.get_absolute_url}}" class="btn btn-primary">Details</a>            
        </div>
    </div>
    <br>
{% endfor %}
<br>
{% endblock content %}

After some struggle I think I managed to make it working. I'm sure it is not perfect but... I appretiate any comments so I can turn it better:

const addBtn = document.getElementById('add-btn')
const modalBody = document.getElementById('model-body')
const siteForm = document.getElementById('site-form')
const alertBox = document.getElementById('alert-box')

const siteName = document.getElementById('id_name')
const siteCity = document.getElementById('id_city')
const csrf = document.getElementsByName('csrfmiddlewaretoken')[0].value

const handleAlerts = (type, msg) => {
    alertBox.innerHTML = `
        <div class="alert alert-${type}" role="alert">
            ${msg}
        </div>
    `
}



addBtn.addEventListener('click', ()=>{
       
    siteForm.addEventListener('submit', e=>{
        if (siteName.value ===''){
            e.preventDefault()
            handleAlerts('danger', 'Name field cannot be left empty')
            siteName.focus()
        }else{ 
            console.log('Campo preenchido')
            e.preventDefault()
            const formData = new FormData()
            formData.append('csrfmiddlewaretoken', csrf)
            formData.append('name', siteName.value)
            formData.append('city', siteCity.value)

            $.ajax({
                type: 'POST',
                url: '/savesite/',
                data: formData,
                success: function(response){                
                    handleAlerts('success', 'Site added')
                    siteForm.reset()
                    window.close();
                },
                error: function(error){
                    console.log(error)
                    handleAlerts('danger', 'Site already exists in that city')
                },
                processData: false,
                contentType: false,
            })            
        }
    })    
})

The HTML is the same.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source