Javascript Element not defined

Asked

Viewed 41 times

0

I’m having trouble running the following Javascript code

//dynamic table 
function chamadaTable(){
    const detailsbody = document.querySelector("#maintenance > tbody");
    console.log(detailsbody);
    loadDetailsbody();
    populateTable();    
}

function loadDetailsbody(){
        const request = new XMLHttpRequest();

        request.open("GET","http://URL/project/consult", true);
        request.onload = () =>{

            try{
                const json = JSON.parse(request.responseText);
                populateTable(json);
            }

            catch(e){
                console.warn("Não foi possivel carregar a tabela!");
            }
        };

        request.send();
    }

function populateTable(json){
    //clear out existing table data
    while(detailsbody.firstChild){
        detailsbody.removeChild(detailsbody.firstChild);
    }
}

I’m getting the following error in the function populateTable:

Uncaught Referenceerror: detailsbody is not defined

being that I am defining detailsbody right at the beginning of the code.

what’s wrong with my code ?

  • evaluating only this section the variable detailsbody is filled in the function chamadaTable that is not called in any corner, maybe this is your problem

  • Hello @Marcelovismari I’m actually calling this method in another Java, I believe that’s not the problem

  • withdraw the const of the variable detailsbody so that it becomes global and makes a test. If it works then declare this variable somewhere that populateTable can access. I believe this is it

1 answer

2


Good afternoon, there are two issues ai, 1-the code is Asynchronous and Function populateTable() is running within Function calling Able() after calling loadDetailsbody() when it should only be in the request.onload method, 2- inside populateTable Voce tries to access detailsbody that does not exist in this context, enter the code :

const detailsbody = document.querySelector("#maintenance > tbody");

out of the called Function Able() for it to exist in a global context

Browser other questions tagged

You are not signed in. Login or sign up in order to post.