Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda