'JavaScript not returning Google Sheets Cell Value

In this code I have declared a variable to get cell value from some spreadsheet owned by me.

And then I used that variable for innerHtml of

element with id "value".

But the web page is not showing any result.

It gives blank page ..

Any idea, what where went wrong ..?

<!DOCTYPE html> 
<html>
<head>
<title>Getting Values from Sheets</title>
</head>
<body>


<p id="value2">Hello World</p>

<p id="value"></p>

<script src="sheets/snippets/snippets.js">

gapi.client.sheets.spreadsheets.values.get({
  spreadsheetId: 1jH0y-PknkZXH7KqjPBWDv98kkBnndGt_GIbdUh_1nRM,
  range: Users!A2
}).then((response) => {
  var result = response.result;
  var numRows = result.values ? result.values.length : 0;
  console.log(`${numRows} rows retrieved.`);
document.getElementById("value").innerHTML = result;
});
</script>

</body>

</html>

Thank You



Solution 1:[1]

Set the value at the time of receiving the response.

gapi.client.sheets.spreadsheets.values.get({
  spreadsheetId: 1jH0y-PknkZXH7KqjPBWDv98kkBnndGt_GIbdUh_1nRM,
  range: users!a2
}).then((response) => {
  var result = response.result;
  var numRows = result.values ? result.values.length : 0;
  console.log(`${numRows} rows retrieved.`);
  document.getElementById("value").innerHTML = result;
});

This is because the next task is executed after sending a request to perform an asynchronous task.

document.getElementById("value").innerHTML = result; code was outside of then().

The var result is not defined at this moment.

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