Ajax Query in Form_Customvalidate

Hi everyone:Following with this thread I have exactly the same issue, making and ajax synchronous request is not workingI have this code in a calendar report Client Scripts->Add/Copy Page->Form_Customvalidate

// Form_CustomValidate
function (fobj) {
    var row = this.value;
    var isValid = false;
    $.ajax({
        url: ew.getApiUrl(["checkplanoperario", row["Operarios"], encodeURIComponent(row["Start"]), encodeURIComponent(row["End"])]),
        type: 'GET',
        async: false, 
        success: function(res) {
            if (res) {
                var datos = JSON.parse(res);
                var textToShow = "";
                for (var i = 0; i < datos.length; i++) {
                    var arrayInterno = datos[i];
                    for (var j = 0; j < arrayInterno.length; j++) {
                        var objetoJSON = arrayInterno[j];
                        var operario = objetoJSON.operario;
                        var fechas = objetoJSON.fechas;
                        textToShow += "Operario: " + operario + " Fechas: " + fechas + "\n";
                    }
                }

                if (textToShow === "") {
                    isValid = true;
                } else {
                    Swal.fire({
                        title: '¿Continue?',
                        text: "Hay personal con trabajos ya asignados para esa(s) fecha(s):\n" + textToShow,
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'Continuar'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            isValid = true;
                        }
                    });
                }
            }
        },
        error: function(xhr, status, error) {
            console.error('Error en la solicitud AJAX:', error);
        }
    });
    
    // Return isValid (true o false) to allow or not the submit
	console.log("isValid?: " + isValid);
    return isValid;
}

But when I press Add button in my modal form, console shows inmediately “isValid?: false” and the form is not submmitedThanks in advance

You may press F12 from your browser, and check whether any Javascript error message from Console section.

HiNo error messages in console, just the “isValid?: false” output from the line: console.log("isValid?: " + isValid);

Adding these console.logs,


// Form_CustomValidate
function (fobj) {
    var row = this.value;
    var isValid = false;
    $.ajax({
        url: ew.getApiUrl(["checkplanoperario", row["Operarios"], encodeURIComponent(row["Start"]), encodeURIComponent(row["End"])]),
        type: 'GET',
        async: false,
        success: function(res) {
            if (res) {
                var datos = JSON.parse(res);
                var textToShow = "";

                // Recorremos los datos obtenidos
                for (var i = 0; i < datos.length; i++) {
                    var arrayInterno = datos[i];
                    for (var j = 0; j < arrayInterno.length; j++) {
                        var objetoJSON = arrayInterno[j];
                        var operario = objetoJSON.operario;
                        var fechas = objetoJSON.fechas;
                        textToShow += "Operario: " + operario + " Fechas: " + fechas + "\n";
                    }
                }
		console.log("text: " + textToShow );   //ADDED
                if (textToShow === "") {
                    // Si no hay colisión, establece isValid en true
                    isValid = true;
                } else {
                    // Si hay colisión, muestra el mensaje de advertencia y espera la confirmación del usuario
					console.log("enter else");
                    Swal.fire({
                        title: '¿Quieres continuar?',
                        text: "Hay personal con trabajos ya asignados para esa(s) fecha(s):\n" + textToShow ,
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'Continuar'
                    }).then((result) => {
						console.log("enter result");  //ADDED
                        if (result.isConfirmed) {
                
							console.log("isConfirmed");  //ADDED
                            isValid = true;
							console.log("isValid inside confirmed: " + isValid);  //ADDED
                        }
                    });
                }
            }
        },
        error: function(xhr, status, error) {
            console.error('Error en la solicitud AJAX:', error);
        }
    });
    
    // Retorna isValid (true o false) para determinar si se permite o no la operación
	console.log("valido?: " + isValid);
    return isValid;
}

Console Output:

[Violation] Forced reflow while executing JavaScript took 34ms
VM2357:50 text: 2024-05-13 - 2024-05-14

VM2357:56 enter else
VM2357:83 valido?: false
VM2357:66 enter result
VM2357:69 isConfirmed
VM2357:71 isValid inside confirmed: true

Be reminded that Ajax is asynchronous, your console.log() is executed first when the Ajax action is being executed. If you want to wait for the Ajax resut, you need to return $.ajax(…).then(…) and the “then” handler should return the isValid.

Thanks.I thought that using ajax with the option async: false, would wait for the answer.Solved using a Promise

// Form_CustomValidate
.setCustomValidate(function (fobj) {
    var row = this.value;

    // Retornar una Promesa
    return new Promise(function(resolve, reject) {
        // Realizar la llamada AJAX
        $.ajax({
            url: ew.getApiUrl(["checkplanoperario", row["Operarios"], encodeURIComponent(row["Start"]), encodeURIComponent(row["End"])]),
            type: 'GET',
            success: function(res) {
                if (res) {
                    var datos = JSON.parse(res);
                    var textToShow = "";

                    // Recorrer los datos obtenidos
                    for (var i = 0; i < datos.length; i++) {
                        var arrayInterno = datos[i];
                        for (var j = 0; j < arrayInterno.length; j++) {
                            var objetoJSON = arrayInterno[j];
                            var operario = objetoJSON.operario;
                            var fechas = objetoJSON.fechas;
                            textToShow += "Operario: " + operario + " Fechas: " + fechas + "\n";
                        }
                    }

                    console.log("textToShow: " + textToShow);

                    if (textToShow === "") {
                        // Si no hay colisión, resolver la Promesa con true
                        resolve(true);
                    } else {
                        // Si hay colisión, mostrar el mensaje de advertencia y esperar la confirmación del usuario
                        Swal.fire({
                            title: '¿Quieres continuar?',
                            text: "Hay personal con trabajos ya asignados para esa(s) fecha(s):\n" + textToShow,
                            icon: 'warning',
                            showCancelButton: true,
                            confirmButtonColor: '#3085d6',
                            cancelButtonColor: '#d33',
                            confirmButtonText: 'Continuar'
                        }).then((result) => {
                            if (result.isConfirmed) {
                                // Si el usuario confirma, resolver la Promesa con true
                                resolve(true);
                            } else {
                                // Si el usuario cancela, resolver la Promesa con false
                                resolve(false);
                            }
                        });
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('Error en la solicitud AJAX:', error);
                resolve(false); // En caso de error, resolver la Promesa con false
            }
        });
    });
})