Home > Blockchain >  Javascript Fetch only works once
Javascript Fetch only works once

Time:12-13

First of all thank you for any help you can give me. I want to be able to dynamically activate/deactivate the status of a partner. enter image description here

On each status change, a Bootstrap modal opens enter image description here

For this I use Fetch() It works fine but only on the first action. If I then try on the same line again it doesn't work anymore. Same on another line. I have to reload the page so that I can redo the activation or deactivation action

Here is my code:

// Activation ou désactivation dynamique d'un partenaire

//On boucle sur les input
document.querySelectorAll(".form-switch-statut-partenaire input").forEach(input => {
    input.addEventListener("change", () => {

        //On récupère l'url de la route edit-statut
        const Url = input.dataset.path;

        const Modal = document.getElementById('exampleModal')
        const Footer = Modal.getElementsByClassName('modal-footer')[0].children[1]

        Footer.addEventListener("click", () => {

            //On lance la requête ajax
            fetch(Url, {
                headers : {
                    
                }
            })
            .then((response) => {
                console.log(response);
                return response.json()
            }).then(data => {
                console.log(data)
             const content = document.querySelector('body');
             content.innerHTML = data.content;
            }).catch((err) => console.log('Erreur : '  err));     
         })
    });
});

I can't find the solution despite my research

CodePudding user response:

Line 122 changes the whole body with the fetched data. This will remove all event listeners you previously set.

Try to change only the HTML that actually changed in the response. Fetching the whole body has probaly some network overhead that can be avoided.

Or move the event listener registration to an init method and call that after swapping out the body.

CodePudding user response:

thank you for your reply I had already tried to modify only the array data using (#formCheck)

}).then(data => {
                console.log(data)
             const content = document.querySelector('#formCheck');
             content.innerHTML = data.content;

The action works but my page is grayed out like my modal is open but it's not visible

enter image description here

  • Related