I have created a function in JavaScript and I don't know why I get undefined
:
$(document).ready(function() {
function actualizaDatosIzquierda() {
var fecha = new Date();
var temperatura_actual = getTemperaturaActual();
$("#temperatura").text("\u00a0"+temperatura_actual+"ºC");
$("#humedad").text("\u00a0"+getHumedadActual()+"%");
$("#estado").text(getEstado());
$("#maximas").text("\u00a0"+getTemperaturaMaxima()+"ºC \u00a0\u00a0"+getHumedadMaxima()+"%");
$("#minimas").text("\u00a0"+getTemperaturaMinima()+"ºC \u00a0\u00a0"+getHumedadMinima()+"%");
$("#ultima-actualizacion").text(fecha.getHours()+":"+fecha.getMinutes());
}
actualizaDatosIzquierda();
setInterval(actualizaDatosIzquierda, 60000);
});
function getTemperaturaActual(){
$.ajax("getLast.php").done(function(msg) {
var res = JSON.parse(msg);
console.log(res["temperatura"].substring(0, 4));
return res["temperatura"].substring(0, 4);
})
}
The funny thing is that in the console the number does come out correctly, but in the HTML element it comes out undefined
.
The string temperatura
is something like this:"23.4"
You get it
undefined
because you are returning a value from an asynchronous operation. You have to understand thecallback
one you provide to the methoddone
(it's a deferred operation) it will be executed when the request has resolved. And until that momentgetTemperaturaActual
it has already been executed and has not returned any value.One solution is to set the temperature value when the asynchronous operation finishes, that is, when it is executed
done
.Another is to use the javascript promises that were introduced in the ES6 version.