0

I am trying to make a function that stops a form from being submitted if a verification via a PHP file says so. This is what I have done:

function vali_data() {
  let resultado = '';
  var data_ini = document.getElementById("data_reserva").value;
  var data_fim = document.getElementById("data_entrega").value;
  var matr = document.getElementById('matriselect').value;

  async function isca() {
    const res = await fetch('includes/vali_datas.php?matr=' + matr + '&data_ini=' + data_ini + '&data_fim=' + data_fim)
    var resultado1 = await res.json();
    return resultado1;
  }

  resultado = isca();

  if (resultado == 1) {
    return false;
  }
}

But the 'resultado' variable only gets 'Object Promise' and of course, the 'if' doesn't work at all...

How can i get the isca() function value? Should i rebuild this in a completely diferent way?

Thank you!

After a sugestion from Jaromanda X i removed the onSubmit from the form, added a onClick on the button, and changed the button type from Submit to button. And changed the js to:

function vali_data() {
    var data_ini = document.getElementById( "data_reserva" ).value;
    var data_fim = document.getElementById( "data_entrega" ).value;
    var matr = document.getElementById( 'matriselect' ).value;

    async function isca() {

        const res = await fetch( 'includes/vali_datas.php?matr=' + matr + '&data_ini=' + data_ini + '&data_fim=' + data_fim );
        var resultado1 = await res.json();
        return resultado1;
    }

    var resultado = isca();
        
    if (resultado == 0 && matr != '' && data_ini != '' && data_fim != ''){
        document.getElementById("n_res_form").submit();;
    }
}

This way it should only submit if all the conditions are met.

But it still doesn't work... The resultado variable is still 'Object Promise'.

  • you can only prevent a form from submitting synchronously ... once you have asynchrony, you're doing it wrong - the way to do it is to ALWAYS prevent the form submitting, and then use AJAX to perform the submit if needed – Jaromanda X Nov 21 '22 at 09:00

0 Answers0