Validate form without deleting the data

1

Good I have a simple form, I want to validate the fields are not empty and that the ID is not duplicated, but at the same time that those fields that are well entered are not deleted. I have the following code.

<script>
            $(document).on("ready", function(){
            mostrar_mensaje();
        });
        var mostrar_mensaje = function() {
            $(".mensaje").fadeOut(4000, function() {
                $(this).html("");
                $(this).fadeIn(4000);
            });
        }
<form action="#" method="post" name="submit" class="form-horizontal" enctype="multipart/form-data">
                <div class="form-group">
                    <h3 class="col-sm-offset-2 col-sm-8 text-center">                   
                    Formulario  </h3>
                </div>

                <div class="form-group">
                    <label for="deceto" class="col-sm-2 control-label">N° Decreto</label>
                    <div class="col-sm-1">
                        <input id="decreto" name="decreto" type="text" class="form-control" autofocus>
                    </div>
                </div>
                <div class="form-group">
                    <label for="fecha" class="col-sm-2 control-label">Fecha</label>
                    <div class="col-sm-2">
                        <input id="fecha" name="fecha" type="date" class="form-control">
                    </div>
                </div>
                <div class="form-group">
                    <label for="materia" class="col-sm-2 control-label">Materia</label>
                    <div class="col-sm-8">
                        <textarea class="form-control" name="materia" id="materia" rows="4"></textarea>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-8">
                        <input type="submit" name="submit" class="btn btn-primary" value="Guardar" />
                    </div>
                   
                </div>
            </form>
            <?php
            include 'conexion.php'
            if (isset($_POST['submit']))
    {
    $decreto = mysqli_real_escape_string($conexion, $_POST['decreto']);
    $fecha = mysqli_real_escape_string($conexion, $_POST['fecha']);
    $materia = mysqli_real_escape_string($conexion, $_POST['materia']);
    $anno=date("Y");
    $decreto_id =$anno.$decreto;
    if (!empty($decreto) || !empty($fecha) || !empty($materia))
        {
        $sql = "SELECT * FROM decreto WHERE decreto_id='$decreto_id'";
        $result = mysqli_query($conexion, $sql);
        $resultCheck = mysqli_num_rows($result);
        if ($resultCheck > 0)
            { ?>    <div class="mensaje" id="mensaje">
        <div class="text-center">
            <div class="alert alert-danger" role="alert">
                <strong>Error</strong> N° decreto ya existe
            </div>
        </div>
    </div>
    <?php
}
  else
    {
    $sqll = "INSERT INTO decreto (decreto_id,anno,materia,decreto,fecha) VALUES ('$decreto_id','$fecha','$materia','$decreto','$anno')";
    $resultt = mysqli_query($conexion, $sqll);
    if ($resultt)
        $query ="INSERT INTO decreto_anno (decreto_id,anno) VALUES ('$decreto_id','$anno')";
     $resulttt = mysqli_query($conexion, $query);
        { ?>
    <div class="mensaje" id="mensaje">
        <div class="text-center">
            <div class="alert alert-success" role="alert">
                <strong>Bien! decreto ingresado exitosamente</strong>
            </div>
        </div>
    </div>
    <?php } } } else { ?>
    <div class="mensaje" id="mensaje">
        <div class="text-center">
            <div class="alert alert-danger" role="alert">
                <strong>Error campos vacios</strong>
            </div>
        </div>
    </div>
    <?php } } ?>

At the moment of pressing the btn save validates me well but the fields are then blank. I have read that with Ajax you can make a little more dynamic the form I will try to apply a bit of Ajax to the form. I hope it is clear greetings be attentive to the post.

    
asked by MoteCL 15.09.2017 в 16:09
source

1 answer

-1

Try to validate the fields from the client with JavaScript, it would be something like:

First, add a id to the form

<form id="myForm" ....>

Access the form from JavaScript and stop the default action (which is to send the form to the server and change the path to "#")

$('#myForm').submit(function(e) {
  e.preventDefault();

  // valida la forma, aquí puedes hacer los envíos por AJAX
  // ejemplo para saber si el id del decreto es válido, envía el valor
  // del decreto y revísalo por php, así se enviaría con JS

  var decretoId = $('#decreto').val();

  $.ajax({ url: '#?decreto=', type: 'GET', dataType: 'json' })
  .success(function(data) {
    // suponiendo que php ha devuelto un json que dice { "valid": false }
    if(!data.valid) {
      decreto.val('');
    }
  });
});

I hope it serves you:)

    
answered by 15.09.2017 в 17:59