How to verify if value exists using Jquery and if so, avoid sending the record?

2

I got some JQuery codes to verify if any value ( cedula in this case) exists in the database.

The system works well, it shows when the card value exists or not, I would like now to prevent the form from being sent, because although it says that it CAN NOT be used because it already exists, it sends the data, and as it is already that stored cedula does not insert.

Registration.php

    <?php
include "conexion.php";
?>
<!doctype html>
<html>
<head>
<link href="styles.css" media="screen" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.3.2.js"></script>

    <meta charset="utf-8">
    <title> </title>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {    
    $('#cedula').blur(function(){

        $('#info').html('<img src="loader.gif" alt="" />').fadeOut(300);

        var cedula = $(this).val();        
        var dataString = 'cedula='+cedula;

        $.ajax({
            type: "POST",
            url: "comprobar_disponibilidad.php",
            data: dataString,
            success: function(data) {
                $('#info').fadeIn(300).html(data);
            }
        });
    });              
});    
</script>
<h1 align ="center">Bienvenido</h1>
<a href ="index.html"><ol>Pagina Principal</ol></a>
<a href ="registrar.php"><ol>Registrar</ol></a>
<a href ="listado.php"><ol>Listado</ol></a>
<a href ="Sancion.php"><ol>Sancion</ol></a>
<form method="POST" action ="procesar.php">     



    <div>
    <label> Ingrese su cedula </label>
    <input type="text" id="cedula" name="cedula">
    <div id="info"></div>
    </div>



    <label> Ingrese su primer nombre </label>
    <input type="text" id="nombre1" name="nombre1"><br/>

    <label> Ingrese su segundo nombre </label>
    <input type="text" id="nombre2" name="nombre2"><br/>

    <label> Ingrese su primer apellido </label>
    <input type="text" id="apellido1" name="apellido1"><br/>

     <label> Ingrese su segundo apellido </label>
    <input type="text" id="apellido2" name="apellido2"><br/>

    <label> Ingrese su rango </label>
    <div><select name="rango">
<?php
global $cone;
$registros=mysqli_query($cone,"select * from rangos");
while ($reg = mysqli_fetch_array($registros))
echo "<option value='$reg[id_rango]'>".$reg[rango]."</option>";


?>
  </select></div>  
    <input type="submit" value="enviar">
</form>

</body>
</html>

Check_availability.php

 <?php
sleep(1);
require_once'conexion.php';
    global $cone;

if($_REQUEST) {
    $cedula = $_REQUEST['cedula'];
    $sql="Select * from personal where cedula = '$cedula'";
if ($result=mysqli_query($cone,$sql))
  {
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);
  //printf("Result set has %d rows.\n",$rowcount); mostrar resultado
 if($rowcount > 0)
        echo '<div id="Error">Cedula ya registrada</div>';
    else
        echo '<div id="Success">Disponible</div>';
}
  }



?>
    
asked by Victor Alvarado 25.01.2017 в 23:55
source

2 answers

2

In your code there are two totally different things that you want to achieve; the dynamic validation of the card through ajax and the final sending of the data when the user sends the completed form.

First define how you want to validate your data; on the server side or on the client side.

Let's see an example on the client side:

Structure your form well:

<form action="procesar.php" method="post" id="myform">
  <input type="text" name="cedula">
  <input type="text" name="nombre">
  <input type="text" name="apellido">
  ...
  <input type="submit" value="enviar">
</form>

A bit of modularization:

function requestValidation(done) {
  $.ajax({
    url: 'validate.php',
    type: 'POST',
    contentType: 'application/json',
    data: { cedula: $('input[name=cedula]').val().trim() }
    success: function(res) { done(null, JSON.parse(res).isValid) },
    error: function(err) { done(err) }
  });
}

Validate the cedula:

$('input[name=cedula]').blur(function() {
  requestValidation(function(err, isValid) {
    if (err) console.error(err);
    if (isValid) // Dar visto bueno
    else // Cédula ya existe
  });
});

Validate data when sending the form

function submit(e) {
  // Recoger los datos:
  var data = {};
  $('#myform').children('input[type=text]').each(function(i, input) {
    var name = $(input).attr('name');
    var value = $(input).val().trim() || undefined;
    data[name] = value;
  });

  // Comprobar validez de los datos:
  var emptyFields = Object.keys(data).some(function(key) {
    return data[key] !== undefined;
  });

  // Evitar enviar el formulario si alguna validación no se cumple:
  if (emptyFields) {
    e.preventDefault();
    return alert('Todos los campos son obligatorios!');
  }

  requestValidation(function(err, isValid) {
    if (err) {
      e.preventDefault();
      alert('Error al intentar validar la existencia de la cedula');
      console.error(err);
    } else if (!isValid) {
      e.preventDefault();
      alert('El número de cédula ya existe');
    }

    // Filtro superado, formulario enviado.
  });
}

$('#myform').submit(submit);

That should be enough with that.

Remember that e.preventDefault() is what prevents the form from being sent, submit is the event that is executed when the user tries to send the form. Send a JSON in response from php so that the ajax can work for you.

If you want to do it from the server you only have to send the data of your form, make the relevant validations from php and send answers according to your validations, if the user has made a mistake, re-render the same page with the message of error.

    
answered by 26.01.2017 / 03:36
source
2

In the JQuery you need to avoid the event and you can better optimize the ajax like PHP.

JQuery has a function ".on ()" , later you prevent the send event with this function" .preventDefault () " and improve ajax.

Example:

$('#formCedula').on("submit", function(event){
   // Evita el envio del formulario
   event.preventDefault();

   // Cache variables
   var divInfo = $("#info");
   var loader = "<img src='loader.gif' />";

   $.ajax({
       type: "POST",
       url: "comprobar_disponibilidad.php",
       beforeSend: divInfo.html(loader);
       data: this.serialize(),
       done: function(data){
          divInfo.html(data);
       }
   })


})

And in PHP:

<?php

$postCedula = ( isset($_POST['cedula']) )? trim($_POST['cedula']) : '';

if( !empty($_POST['cedula']) ) ){
  require_once'conexion.php';

  $sql = "SELECT * FROM personal WHERE cedula = '$cedula'"
  $result = mysqli_query($connection, $sql);
  $counter = mysqli_num_rows($result);

  if($result AND $counter){ // Cero 0, PHP lo toma como FALSE
     echo "Cedula ya existe";
  }
  else {
     mysqli_free_result($result);
     $sql = "INSERT INTO personal (cedula) VALUES ('$cedula')";
     if( mysqli_query($connection, $sql) ){
        echo "Exito, se guardo cedula $cedula";
     }
     else {
        echo "Error, no se guardo cedula $cedula";
     }         
  }
}
else {
   echo "Falto cedula...";
}

Obviously there is a lot missing in the 2 codes, in the backend validations, sanitation, optimization of codes, etcera.

The frontend can be optimized better with HTML5, JQuery and some javascript tools, I hope you will be a guide.

    
answered by 26.01.2017 в 04:08