Validating form with onsubmit and javascript

1

I'm having a problem with validating a form I'm using ajax to validate fields

Problem the onsubmit expects a boolean type return and I am not able to make that return

I put a counter inside the .done (function (html)) but this counter works only inside it when I try to retrieve the counter value outside .done (function (html) it is zeroed follow my code

function validaFormALterar(acao) {
    var opc = acao;
    var erro = 0;

    var url = 'model/validarSenha.php';
    var Csenha = 'Csenha=' + $('#Csenha').val();

    var dados = Csenha;

    $.ajax({
        url: url,
        data: dados,
        cache: false
    }).done(function (html) {
        if (html == 'erro') {
            //não consigo pegar o valor desse ERRO fora do DONE
            erro++;
        }
    });

    //erro sempre chegando 0
    console.log("Erro nº " + erro);

    if(erro==0){
        return true;
    }
}
    
asked by anonymous 06.11.2015 / 13:35

2 answers

1

If you need to perform validation through an AJAX request, then define a callback function as a parameter in the validaFormALterar method.

function validaFormAlterar(acao, callback) {
  var opc = acao;
  var isValid = true;

  var url = 'model/validarSenha.php';

  var Csenha = 'Csenha=' + $('#Csenha').val();
  var dados = Csenha;

  $.ajax({
    url: url,
    data: dados,
    cache: false
  }).done(function (html) {
    if (html == 'erro') {
      isValid = false;
    }
    callback(isValid);
  });
}

The call to the method to validateFormAlterar will be done as follows, passing a function that receives as a parameter whether the validation was successful or not, this will be our callback function;

You should continue processing the page in the body of this function

validaFormAlterar("minha ação", function (isValid) {
  if (isValid) {
    //valido com sucesso
  } else {
    //ocorreu erros de validação.
  }
});

You can even make the AJAX function synchro as suggested Yure Pereira , but I do not advise you to do This will keep the main advantage of using an AJAX request.

    
06.11.2015 / 14:01
0

Make a non-asynchronous ajax request, because when the asynchronous code flow continues to be interpreted even though the request has not yet returned the server response, thus causing the done function to be executed after the block of code that is outside of it, where you can not get the error ++ .

function validaFormALterar(acao) {
  var opc = acao;
  var erro = 0;

  var url = 'model/validarSenha.php';

  var Csenha = 'Csenha=' + $('#Csenha').val();
  var dados = Csenha;

  $.ajax({
    url: url,
    data: dados,
    cache: false,
    async: false,
  }).done(function (html) {
    if (html == 'erro') {
      //não consigo pegar o valor desse ERRO fora do DONE
      erro++;
    }
  })
  //erro sempre chegando 0
  console.log("Erro nº " + erro);
  if(erro==0){
    return true;
  }

}
    
06.11.2015 / 13:48