I have a function in javascript on a page, which queries a data through the controller .. which then goes to the BD .. etc .. the issue, is that the function in javascript, which is called in the event $ (document) .ready (function (), does not return anything to me .. or actually returns undefines.) investigating a bit on the subject, I realized that the ajax call that is inside the function, delays in bringing the result .. that is, the page does not wait for it (obviously, because it is ajax) and when it needs to process the result, it only has the undefined value. I read there, that you have to consult for a readystatus == 4. but I'm half lost in this ... precisely, where should I consult this? when I make the call to the function ??, or in the function ?. The code is as follows:
$(document).ready(function () {
// si llega aca, significa que el profesional tiene alñ menos 1 turno.
var IdProfesional = 0;
var turnoSelecc = fnObtieneTurnos(IdProfesional);
alert("turnoSelecc = " + turnoSelecc);
// aca va el resto de la funcion que usa el valor turnoSelecc y que llega con
// undefined
});
// esta es la funcion que tiene la llamada ajax
<script type="text/javascript">
//Busca los turnos disponibles para el profesional y los despliega en pantalla
function fnObtieneTurnos(IdProfesional) {
var turnoSeleccionado = 0;
var parametrosAjax = {
"IdProfesional": IdProfesional
};
$.ajax(
{
type: 'POST',
data: JSON.stringify(parametrosAjax),
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: '/Selecciona/GetTurnos',
success: function (turnos) {
if (turnos.length > 0) {
if (turnos.length > 1) {
var comboTurnos = "<select>";
$.each(turnos, function (idx, turno) {
comboTurnos += "<option value='" + turno.Value + "'>" + turno.Text + "</option>";
});
comboTurnos += "</select>";
$("#turnosDiv").append(comboTurnos);
// aca retornamos el primer elemento
turnoSeleccionado = turnos[0].Value;
}
else {
// aca hay un solo turno
var comboTurnos = "";
$.each(turnos, function (idx, turno) {
comboTurnos = turno.Text;
});
$("#turnosDiv").append(comboTurnos);
turnoSeleccionado = turnos[0].Value;
}
}
else {
var msgNoHayTurnos = "No se turnos disponibles para este usuario";
$('#turnosProf').html(msgNoHayTurnos);
turnoSeleccionado = 0;
}
},
error: function (error) {
var msgNoHayTurnos = "No se turnos disponibles para este usuario";
$('#turnosProf').html(msgNoHayTurnos);
turnoSeleccionado = 0;
}
});
return turnoSeleccionado;
}
</script>
Can someone help me with this?