Control java window open and close

I have a modal window that allows me to create new instance but I’m getting some strnge behaviour:

  • If I get error because the site already exists the window closes
  • If I manage to insert 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>
    `
}

function confirmExit() {
    return "You have attempted to leave this page. Are you sure?"
}

addBtn.addEventListener('click', ()=>{
       
    siteForm.addEventListener('submit', e=>{
        if (siteName.value ===''){
            handleAlerts('danger', 'Name field cannot be left empty')
            siteName.focus();
            window.onbeforeunload = confirmExit;
        }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()                          
                },
                error: function(error){
                    console.log(error)
                    handleAlerts('danger', 'Site already exists in that city')
                },
                processData: false,
                contentType: false,
            })
            window.close();
        }
    })    
})