Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
Javascript global variable won't change after method

If the button is pressed it should first get a value from a SELECT SQL statement and use the result for a INSERT. i got the global variable:

var CostperMovie; 

This is the get function that saves the value in CostperMovie:

const movienumber= req.body.movienumber;    
var sql = "SELECT costs FROM movieWHERE movienumber= ' " + movienumber+" ' ";
connection.query(sql, (err, res)=>{
     if(err)throw err;
        CostperMovie = JSON.parse(JSON.stringify(res[0].costs));
        console.log(CostperMovie);
  });

These are the variables that should be inserted but the variable CostperMovie stays undefined:

const clientID= req.body.clientID;
const begin= req.body.begin;
const end= req.body.end;
const begin1= new Date(req.body.begin).valueOf();
const end1= new Date(req.body.end).valueOf();
const diff = Math.abs(rueckgabedatum1-ausleihdatum1);
const diffDays = Math.ceil(diff / (1000*60*60*24));
const totalCosts= diffDays*CostperMovie;

This is the INSERT with the variables:

const sqlInsert = "INSERT INTO ausleihen (movienumber, clientID, begin, end,totalCosts) VALUES (?,?,?,?,?);";
connection.query(sqlInsert, [movienumber, clientID, begin, end,totalCosts], (err, result)=>{
    console.log(err);
});

So why stays the variable CostperMovie undefined or how can I fix it?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

What is stored in res[0].costs? Do you see the actual data coming in res? Is it valid json? Also, probably, the data you want to be extracted from the json, just doesn't exist. It may be just res.costs or res[0][0].costs etc.

or try something like this:

const result = JSON.parse(JSON.stringify(res));
CostperMovie = result[0].costs;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda