preventDefault() Does it not work together with ajax/josn?

Asked

Viewed 34 times

0

I’m having this problem that preventDefault(), does not work for anything within ajax. I can see perfectly in the CONSOLE.LOG that it returns false, already tested with Alert to ensure that it does the if path and works.

$.ajax({
    url: 'php/eng-verifica-email.php',
    type: 'POST',
    dataType: 'json',
    data:{"email_a" :email_a.val()},
    success: function(data) {
        console.log("VERIFICA EMAIL: " + data)
        if (data == "false") {
            document.getElementById("msgerro").innerHTML="Este email já está sendo utilizado";
            form_reg.email_reg.focus()
            event.preventDefault()
        }else {

        }
    }
})

I’m using other verification structures that work perfectly as:

if (nome == "") {
var div = document.getElementById("msgerro")
div.innerHTML = "O nome deve ser preenchido!"
form_reg.pname_reg.focus()
event.preventDefault()  

It doesn’t really let the screen update, but if I complete all fields, even with the existing email in the bank, because of the ajax that won’t let me use the preventDefault() it send the form. From now on, thank you.

var form_cadastrar = document.querySelector('#form_reg');

form_cadastrar.onsubmit = function(event) {

  var nome = form_reg.pname_reg.value
  var email = form_reg.email_reg.value
  var cpf = form_reg.cpf_reg.value
  var rg = form_reg.rg_reg.value
  var senha = form_reg.pass_reg.value
  var confsenha = form_reg.confpass_reg.value
  var telefone = form_reg.tel_reg.value
  var endereco = form_reg.end_reg.value
  var estado = form_reg.esta_reg.value
  var emissor = form_reg.emi_reg.value
  var chave = form_reg.key_reg.value

  usuario = email.substring(0, email.indexOf("@"));
  dominio = email.substring(email.indexOf("@") + 1, email.length);

  if ((usuario.length >= 1) &&
    (dominio.length >= 3) &&
    (usuario.search("@") == -1) &&
    (dominio.search("@") == -1) &&
    (usuario.search(" ") == -1) &&
    (dominio.search(" ") == -1) &&
    (dominio.search(".") != -1) &&
    (dominio.indexOf(".") >= 1) &&
    (dominio.lastIndexOf(".") < dominio.length - 1)) {

    var email_a = $('#email')
    $.ajax({
      url: 'php/eng-verifica-email.php',
      type: 'POST',
      dataType: 'json',
      data: {
        "email_a": email_a.val()
      },
      success: function(data) {
        console.log("VERIFICA EMAIL: " + data)
        if (data == "false") {
          document.getElementById("msgerro").innerHTML = "Este email já está sendo utilizado";
          form_reg.email_reg.focus()
          event.preventDefault()
        } else {

        }
      },
      error: function(responseText) {
        console.log(responseText)
      }
    })
  } else {
    document.getElementById("msgerro").innerHTML = "<Email não válido";
    form_reg.email_reg.focus()
    event.preventDefault()
  }

  if (nome == "") {
    var div = document.getElementById("msgerro")
    div.innerHTML = "O nome deve ser preenchido!"
    form_reg.pname_reg.focus()
    event.preventDefault()
  } else {
    var div = document.getElementById("msgerro")
    div.innerHTML = ""

  }

  if (nome.length <= 7) {
    var div = document.getElementById("msgerro")
    div.innerHTML = "Digite seu nome corretamente!"
    form_reg.pname_reg.focus()
    event.preventDefault()
  } else {
    var div = document.getElementById("msgerro")
    div.innerHTML = ""

  }

  if (chave == 0) {
    if (cpf == "") {
      var div = document.getElementById("msgerro")
      div.innerHTML = "O CPF deve ser preenchido!"
      form_reg.cpf_reg.focus()
      event.preventDefault()
    } else {
      var cpf_a = $('#cpf_reg')
      $.ajax({
        url: 'php/eng-verifica-cpf.php',
        type: 'POST',
        dataType: 'json',
        data: {
          "cpf_a": cpf_a.val()
        },
        success: function(data) {
          console.log("VERIFICA CPF: " + data)
          if (data == "false") {
            var div = document.getElementById("msgerro")
            div.innerHTML = "Este CPF ja esta sendo utilizado!"
            form_reg.cpf_reg.focus()
            event.preventDefault()
          } else {

          }
        }
      })
    }

    if (cpf.length != 14 ||
      cpf == "000.000.000-00" ||
      cpf == "111.111.111-11" ||
      cpf == "222.222.222-22" ||
      cpf == "333.333.333-33" ||
      cpf == "444.444.444-44" ||
      cpf == "555.555.555-55" ||
      cpf == "666.666.666-66" ||
      cpf == "777.777.777-77" ||
      cpf == "888.888.888-88" ||
      cpf == "999.999.999-99") {
      var div = document.getElementById("msgerro")
      div.innerHTML = "CPF não valido!"
      form_reg.cpf_reg.focus()
      event.preventDefault()
    } else {
      var div = document.getElementById("msgerro")
      div.innerHTML = ""
    }

    cpf_temp = cpf.replace(".", "");
    cpf_temp = cpf_temp.replace(".", "");
    cpf_temp = cpf_temp.replace("-", "");

    var soma = 0
    for (var i = 1; i <= 9; i++) soma = soma + parseInt(cpf_temp.substring(i - 1, i)) * (11 - i);
    resto = (soma * 10) % 11;

    if ((resto == 10) || (resto == 11)) resto = 0;
    if (resto != parseInt(cpf_temp.substring(9, 10))) {
      var div = document.getElementById("msgerro")
      div.innerHTML = "CPF não valido!"
      form_reg.cpf_reg.focus()
      event.preventDefault()
    }

    var soma = 0
    for (i = 1; i <= 10; i++) soma = soma + parseInt(cpf_temp.substring(i - 1, i)) * (12 - i);
    resto = (soma * 10) % 11;

    if ((resto == 10) || (resto == 11)) resto = 0;
    if (resto != parseInt(cpf_temp.substring(10, 11))) {
      event.preventDefault()
    }



    if (rg == "") {
      var div = document.getElementById("msgerro")
      div.innerHTML = "O número de documento deve ser preenchido!"
      form_reg.rg_reg.focus()

      event.preventDefault()
    } else {
      var rg_a = $('#rg_reg')
      $.ajax({
        url: 'php/eng-verifica-rg.php',
        type: 'POST',
        dataType: 'json',
        data: {
          "rg_a": rg_a.val()
        },
        success: function(data) {
          console.log("VERIFICA DOCUMENTO: " + data)
          if (data == "false") {
            var div = document.getElementById("msgerro")
            div.innerHTML = "Este Documento já está sendo utilizado!"
            form_reg.rg_reg.focus()
            event.preventDefault()
          } else {

          }
        }
      })
    }

    if (emissor == "") {
      var div = document.getElementById("msgerro")
      div.innerHTML = "O emissor deve ser preenchido!"
      form_reg.emi_reg.focus()
      event.preventDefault()
    } else {
      var div = document.getElementById("msgerro")
      div.innerHTML = ""

    }
    if (emissor.length <= 1) {
      var div = document.getElementById("msgerro")
      div.innerHTML = "O emissor deve ser preenchido corretamente!"
      form_reg.emi_reg.focus()
      event.preventDefault()
    } else {
      var div = document.getElementById("msgerro")
      div.innerHTML = ""

    }
  }

  if (chave == 1) {
    if (cpf == "") {
      var div = document.getElementById("msgerro")
      div.innerHTML = "O CNPJ deve ser preenchido!"
      form_reg.cpf_reg.focus()

      event.preventDefault()
    } else {
      var div = document.getElementById("msgerro")
      div.innerHTML = ""

    }

    cpf_temp = cpf.replace(".", "")
    cpf_temp = cpf_temp.replace(".", "")
    cpf_temp = cpf_temp.replace("/", "")
    cpf_temp = cpf_temp.replace("-", "")

    if (cpf_temp.length !== 14) {
      var div = document.getElementById("msgerro")
      div.innerHTML = "CNPJ não valido!"
      form_reg.cpf_reg.focus()
      event.preventDefault()
    } else {
      var div = document.getElementById("msgerro")
      div.innerHTML = ""
    }

    d1 = cpf_temp.substr(12, 1)
    d2 = cpf_temp.substr(-1)

    cnpj_temp = cpf_temp.substr(0, 12)

    var array = cnpj_temp.split('')

    cnpj_0 = array[0] * 6
    cnpj_1 = array[1] * 7
    cnpj_2 = array[2] * 8
    cnpj_3 = array[3] * 9
    cnpj_4 = array[4] * 2
    cnpj_5 = array[5] * 3
    cnpj_6 = array[6] * 4
    cnpj_7 = array[7] * 5
    cnpj_8 = array[8] * 6
    cnpj_9 = array[9] * 7
    cnpj_10 = array[10] * 8
    cnpj_11 = array[11] * 9

    soma_d1 = cnpj_0 + cnpj_1 + cnpj_2 + cnpj_3 + cnpj_4 + cnpj_5 + cnpj_6 + cnpj_7 + cnpj_8 + cnpj_9 + cnpj_10 + cnpj_11

    multplica_d1 = soma_d1 % 11

    cnpj_0 = array[0] * 5
    cnpj_1 = array[1] * 6
    cnpj_2 = array[2] * 7
    cnpj_3 = array[3] * 8
    cnpj_4 = array[4] * 9
    cnpj_5 = array[5] * 2
    cnpj_6 = array[6] * 3
    cnpj_7 = array[7] * 4
    cnpj_8 = array[8] * 5
    cnpj_9 = array[9] * 6
    cnpj_10 = array[10] * 7
    cnpj_11 = array[11] * 8
    cnpj_12 = d1 * 9

    soma_d2 = cnpj_0 + cnpj_1 + cnpj_2 + cnpj_3 + cnpj_4 + cnpj_5 + cnpj_6 + cnpj_7 + cnpj_8 + cnpj_9 + cnpj_10 + cnpj_11 + cnpj_12

    multplica_d2 = soma_d2 % 11

    if (multplica_d1 == 10) {
      multplica_d1 = 0
    }
    if (multplica_d2 == 10) {
      multplica_d2 = 0
    }

    if (multplica_d1 != d1) {
      var div = document.getElementById("msgerro")
      div.innerHTML = "CNPJ não valido!"
      form_reg.cpf_reg.focus()

      event.preventDefault()
    } else {
      var div = document.getElementById("msgerro")
      div.innerHTML = ""
    }
    if (multplica_d2 != d2) {
      var div = document.getElementById("msgerro")
      div.innerHTML = "CNPJ não valido!"
      form_reg.cpf_reg.focus()
      event.preventDefault()
    } else {
      var cpf_a = $('#cpf_reg')
      $.ajax({
        url: 'php/eng-verifica-cpf.php',
        type: 'POST',
        dataType: 'json',
        data: {
          "cpf_a": cpf_a.val()
        },
        success: function(data) {
          console.log("VERIFICA CNPJ: " + data)

          if (data == "false") {
            var div = document.getElementById("msgerro")
            div.innerHTML = "Este CNPJ ja esta sendo utilizado!"
            form_reg.cpf_reg.focus()
            event.preventDefault()
          } else {

          }
        },
        error: function(responseText) {
          console.log(responseText)
        }
      })
    }

  }

  if (telefone == "") {
    var div = document.getElementById("msgerro")
    div.innerHTML = "O telefone deve ser preenchido!"
    form_reg.tel_reg.focus()
    event.preventDefault()
  } else {
    var div = document.getElementById("msgerro")
    div.innerHTML = ""

  }
  if (telefone.length <= 12) {
    var div = document.getElementById("msgerro")
    div.innerHTML = "O telefone deve ser preenchido corretamente!"
    form_reg.tel_reg.focus()
    event.preventDefault()
  } else {
    var div = document.getElementById("msgerro")
    div.innerHTML = ""
  }
  if (endereco == "") {
    var div = document.getElementById("msgerro")
    div.innerHTML = "O endereço deve ser preenchido!"
    form_reg.end_reg.focus()
    event.preventDefault()
  } else {
    var div = document.getElementById("msgerro")
    div.innerHTML = ""
  }
  if (endereco.length <= 4) {
    var div = document.getElementById("msgerro")
    div.innerHTML = "O endereço deve ser preenchido corretamente!"
    form_reg.end_reg.focus()
    event.preventDefault()
  } else {
    var div = document.getElementById("msgerro")
    div.innerHTML = ""
  }
  if (estado == "") {
    var div = document.getElementById("msgerro")
    div.innerHTML = "O estado deve ser preenchido!"
    form_reg.esta_reg.focus()
    event.preventDefault()
  } else {
    var div = document.getElementById("msgerro")
    div.innerHTML = ""
  }
  if (estado.length == 1) {
    var div = document.getElementById("msgerro")
    div.innerHTML = "O estado deve ser preenchido!"
    form_reg.esta_reg.focus()
    event.preventDefault()
  } else {
    var div = document.getElementById("msgerro")
    div.innerHTML = ""
  }
  if (senha == "") {
    var div = document.getElementById("msgerro")
    div.innerHTML = "Senha deve ser preenchida!"
    form_reg.pass_reg.focus()
    event.preventDefault()
  } else {
    var div = document.getElementById("msgerro")
    div.innerHTML = ""
  }
  if (senha.length <= 7) {
    var div = document.getElementById("msgerro")
    div.innerHTML = "A senha deve conter no mínimo 8 digitos!"
    form_reg.pass_reg.focus()
    event.preventDefault()
  } else {
    var div = document.getElementById("msgerro")
    div.innerHTML = ""
  }
  if (confsenha == "") {
    var div = document.getElementById("msgerro")
    div.innerHTML = "Preencha o campo repita sua senha!"
    form_reg.confpass_reg.focus()
    event.preventDefault()
  } else {
    var div = document.getElementById("msgerro")
    div.innerHTML = ""
  }
  if (senha != confsenha) {
    var div = document.getElementById("msgerro")
    div.innerHTML = "Senhas não conferem"
    form_reg.confpass_reg.focus()
    event.preventDefault()
  } else {
    var div = document.getElementById("msgerro")
    div.innerHTML = ""
  }
}
<!DOCTYPE html>
<html>

<head>
  <?php
		$titulo_page = "Cadastro - Ilhabela";
		require 'php/head.php'; 
	?>
</head>

<body>
  <?php  
		require_once 'php/nav-home.php';
	?>
  <div id="fundo-registro">
    <div class="container container-reg-form">
      <h1 class="titulo-index flow-text">
        ME CADASTRAR
      </h1>
      <div class="row row-reg-form fadeIn">
        <form class="col s12" method="post" name="form_reg" id="form_reg" action="php/eng-registro.php">
          <div id="msgerro">

          </div>
          <div class="row">
            <div class="col s12">
              <label for="email">Email</label>
              <input id="email" type="text" class="" name="email_reg" maxlength="50">
            </div>
          </div>
          <div class="row">
            <div class="col s12">
              <label for="first_name">Nome Completo</label>
              <input id="pname_reg" type="text" class="validate" name="pname_reg" maxlength="60">
            </div>
          </div>
          <div class="row">
            <div class="col s4 c_doc">
              <div class="switch">
                <label>
							 	<span class="key-color-cpf color-blue">CPF</span>
							      <input name="key_reg" value="0" type="checkbox" onchange="cpfCnpj()">
							      <span class="lever"></span>
							    <span class="key-color-cnpj">CNPJ</span>
							 </label>
              </div>
              <input id="cpf_reg" type="text" class="validate" name="cpf_reg" maxlength="14" minlength="14">
            </div>
            <div class="col s4 n_doc">
              <label for="first_name">Número do documento</label>
              <input id="rg_reg" type="text" class="validate" name="rg_reg" maxlength="13" minlength="13">
            </div>
            <div class="col s2 t_doc">
              <label for="first_name">Tipo DOC</label>
              <select name="tipo_doc">
                <option value="RG">RG</option>
                <option value="CNH">CNH</option>
                <option value="CTPS">CTPS</option>
                <option value="Outro">Outro</option>
              </select>
            </div>
            <div class="col s2 e_doc">
              <label for="first_name">Emissor</label>
              <input id="emi_reg" type="text" class="validate" name="emi_reg" maxlength="4" minlength="2">
            </div>
          </div>
          <div class="row">
            <div class=" col s3">
              <label for="telefone">Telefone</label>
              <input id="tel_reg" type="text" class="validate" name="tel_reg" maxlength="25">
            </div>
            <div class=" col s7">
              <label for="cndereco">Endereço</label>
              <input id="end_reg" type="text" class="validate" name="end_reg" maxlength="50">
            </div>
            <div class=" col s2">
              <label for="cndereco">Estado</label>
              <select name="esta_reg">
                <option value="SP">SP</option>
                <option value="AC">AC</option>
                <option value="AL">AL</option>
                <option value="AP">AP</option>
                <option value="AM">AM</option>
                <option value="BA">BA</option>
                <option value="CE">CE</option>
                <option value="DF">DF</option>
                <option value="ES">EP</option>
                <option value="GO">GO</option>
                <option value="MA">MA</option>
                <option value="MT">MT</option>
                <option value="MS">MS</option>
                <option value="MG">MG</option>
                <option value="PA">PA</option>
                <option value="PB">PB</option>
                <option value="PR">PR</option>
                <option value="PE">PE</option>
                <option value="PI">PI</option>
                <option value="RJ">RJ</option>
                <option value="RN">RN</option>
                <option value="RS">RS</option>
                <option value="RO">RO</option>
                <option value="RR">RR</option>
                <option value="SC">SC</option>
                <option value="SE">SE</option>
                <option value="TO">TO</option>
                <option value="EX">Estrangeiro</option>
              </select>
            </div>
          </div>
          <div class="row">
            <div class=" col s4">
              <label for="password">Senha</label>
              <input id="password" type="password" class="validate" name="pass_reg" maxlength="25">
            </div>
            <div class=" col s4">
              <label for="password">Repita a senha</label>
              <input id="confpassword" type="password" class="validate" name="confpass_reg" maxlength="25">
            </div>

            <div class="col s4">
              <button type="submit" class="btn" value="cadastrar" style="width: 100%; padding: 0; height: 70px;">
							CADASTRAR</button>

            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
  <?php  
		require 'php/footer.php';
	?>
</body>
<script type="text/javascript" src="js/eng-registro.js"></script>

</html>

  • you can show the function within which this ajax runs and the way the form is submitted?

  • The .preventDefault() is to cancel a cancellable event. Your code does not show any event call. You probably want to cancel a Ubmit. If so, the .preventDefault() should be in the event function and not in AJAX.

  • I’m calling up the event "form_cadastrar.onsubmit = Function(Event)" until msm that if n were calling n would work. preventDefault() with noem blank. Only n could put the entire code here

  • Put the code here that we help format

  • My apologies, I’m new to this forum

  • Ajax is asynchronous, there is no way to interrupt an event that has already occurred, read more at: https://answall.com/q/116153/3635

Show 1 more comment

1 answer

0

I managed to solve the problem, I don’t know exactly if it can be called "gambiarra", but the point is that . preventDefault() definitely doesn’t work within ajax, I don’t know exactly pq, but neither does "Return false" work. What I conclude after a week with this problem:

If I can’t stop the page advance in ajax, but I can show the error message inside the DIV with the ID:msgerro, I can check the value inside the DIV, if the message is == a "This email is already being used" Event.preventDefault(). Follows the code:

''' var erro_json = $('#msgerro').html() //puxa valor da DIV
''' if (erro_json == "Este email já está sendo utilizado!") {
'''  event.preventDefault()
''' }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.