'JavaScript function with Ajax request returns always the wrong value
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?
Solution 1:[1]
At a quick glance you are trying to reassign the value of a const mo_time. Have you tried using let?
Solution 2:[2]
@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
Solution 3:[3]
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);
}
Solution 4:[4]
For this case i prefer use the async/await approache with promises. Ajax request is asynchronous. When you call getTime method in a synchronous manner you get 0 value which follows from const mo_time = 0; in second line of code.
Try it:
function getTime(idx) {
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: '/currdata',
data: '',
contentType: 'application/json'
}).done((result) => resolve(result)).fail((error) => reject(error));
});
}
async function main() {
const data = await getTime(1);
console.log(data['time']);
}
main();
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
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 | Hollman Barahona |
| Solution 2 | rishabh thakkar |
| Solution 3 | Michael |
| Solution 4 | Emerex |
