I am a newbe in JavaScript and I want to create a website with Flask, JavaScript and Python. Currently I a have a problem. I call a JS function from my html page. That function creates an Ajax request and should return a value.
function getTime (idx) {
const mo_time = 0;
$.ajax({
type: 'POST',
url: '/currdata',
data: '',
contentType: 'application/json'
})
.done( (data) => {
//console.log("success");
mo_time = data["time"];
})
.fail( (data) => {
//Data acquisition failure
//console.log("error");
mo_time = 0;
});
return (mo_time);
}
The request is successfully but I always got 0 as return value. How can I put the data["time"] value into the mo_time variable?
At a quick glance you are trying to reassign the value of a const mo_time. Have you tried using let?
@Michael Constants are block-scoped. You can variables declared using the let keyword. The value of a constant can't be changed through reassignment
For scope please check this: scope in javascript
Please check these references. let var const
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
Yes I tried it. Meanwhile I found the solution. I have to add a async: false to the ajax request. The problem was the asynchronus call. I did the return while the request was not finished.
function getTime (idx) {
var mo_time = 0;
$.ajax({
type: 'POST',
url: '/currdata',
data: '',
async: false,
contentType: 'application/json'
})
.done( (data) => {
//console.log("success");
mo_time = data["time"];
})
.fail( (data) => {
//Data acquisition failure
//console.log("error");
mo_time = 0;
});
return (mo_time);
}