Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!