I need to validate a user and password before a form is sent. For that I use jQuery and Ajax. But I have problems passing the 'estado'value outside the anonymous function.
This is the code:
function tx_oriconvocatorias_pi1_validarFormPost(){
var x=document.forms["form_postulante"]["pass_un"];
if (x.value==null || x.value==""){
alert("Por favor ingrese su contraseña.");
return false;
}
var $j = jQuery.noConflict();
var cun = $j('#correo_un').val();
var pun = $j('#pass_un').val();
var estado = null;
$j.ajax({
type: 'POST',
data: 'eID=ori_convocatorias_formPost&correo_un='+cun+'&pass_un='+pun,
success: function(datos){
if(datos!=1){
alert ("La contraseña ingresada no es válida");
}
estado = datos;
alert(estado);
},
});
alert(estado);
if (estado!=1){
return false;
}
}
I notice that the first alert(estado)(outside) returns null and then the second alert(estado) (inside) returns 'datos', so the last alert(estado) in the code is executed first and always my function returns false.
I don’t know how to evaluate 'estado' after execute the Ajax code and not before.
Thanks in advance for the help.
You can’t. You are doing an asynchronus request so your function ends before the result of the ajax call has returned.
You can force the call to be synchronus :
or you can return false, and submit your form manually.