'Javascript global variable won't change after method [duplicate]

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?



Solution 1:[1]

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;

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 curveball