prevent submit with ajax

0

I have the following form:

<form id="frm-registrarusuario" action="../php/usuario.php" method="post">
  <input name="usuario" id="usuario" type="text">
  <input name="clave" id="clave" type="text">
  <button type="submit" name="submit" >Registrar</button>
</form>

The user.php file:

if(isset($_POST["validarUsuario"])){
    header('content-type: text/json');
    $usuario = $_POST["usuario"];
    $where = array("usuario"=>$usuario);
    if($obj -> validarUsuario("usuario",$where))
    {
        $data["respuesta"] = "EXISTE";
        $data["mensaje"] = "¡ERROR!, El usuario ingresado ya existe";
    }else{
        $data["respuesta"] = "NOEXISTE";
    }
    echo json_encode($data);
}

the jquery code:

$(document).ready(function () {
    $("#frm-registrarusuario").on("submit",function (e) {
        e.preventDefault();
        var usuario = $("#usuario").val();
        $.ajax({
            method:'post',
            url:'../php/usuario.php',
            data:{
                usuario:usuario,
                validarUsuario:1
            },
            dataType:'json',
            success:function (data) {
                if(data["respuesta"]=="EXISTE"){
                    alert(data["mensaje"]);
                    return false;
                }
                if(data["respuesta"]=="NOEXISTE"){
                    return true;
                }
            }
        });

    });
});

What I intend to do is that if the user exists, the form does not allow sending data, however when the user exits, he still sends the form. It seems that the ajax runs at the end of everything, after sending the form. Any idea how to solve it?

    
asked by Raphael 23.12.2017 в 00:55
source

1 answer

0
  

In your specific case, you can not prevent the sending of the data,   you need by business logic. If you can prevent the   default action of the submit.

If you want to validate the existence of the user before registering, why not send the request to the server as you are doing? By doing so, you allow the server to perform the validation and if it does not exist it registers it, otherwise it exists, for example you can return your information and update the content of the page with that data.

By default, as you have it, ajax does not refresh the page:

$("#frm-registrarusuario").on("submit",function (e) {
            e.preventDefault(); 
           // PERFECTO-> Capturas el evento y evitas que refresque haciendo la llamada con ajax.
            $.ajax({
            ...

The problem is with the returns, these can cause a refresh of the DOM by reloading the page, there you should put functionality that you can take advantage of with the ajax call as the alerts you already do.

    
answered by 23.12.2017 в 02:13