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

176
Views
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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

At a quick glance you are trying to reassign the value of a const mo_time. Have you tried using let?

about 4 years ago · Juan Pablo Isaza Report

0

@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

about 4 years ago · Juan Pablo Isaza Report

0

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);    
}
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!