Giving this method, I declare a variable “answer” that will contain a String value. Then I call a getJSON method. I want to update the mentioned variable inside that method:
function verificarRespuestasAjax(pregunta, pinId, respuesta, index){
var answer = pregunta;
$.getJSON("../usuarios/comparar_respuestas_JSON", {pinId: pinId, preguntaId: pregunta, respuesta: respuesta.val() }, function(verifRespuestas){
if(verifRespuestas){
$("#mensajeError"+index).remove();
answer += 'true';
}else{
if (!$("#mensajeError"+index).length > 0)
$(respuesta).after('<em id="mensajeError'+index+'">*La respuesta no coincide</em>');
answer += 'false';
}
});
return answer;
}
How should I do that?
Thanks in advance!
You did update the variable. The only issue here is that the
getJSONcall is asynchronous. At the time thealert()executes, the function callback forgetJSONhas not been called.You will want to put your
alert(answer)code in a function that you call from your JSON callback.