Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda