How to validate php form

-3

Good I am new in PHP I am realizing a form that I register with the bd sql server

Within the form you only have these fields I have an inconvenience I hope you can help me every time I enter the ID or the name and I pulse register and as there is a validation within the PHP what I have written is deleted. and I see that I update what I would like to know how I can validate a form without updating the page and what I have written before it remains and it is not deleted

Dni : <input type="text" name="t1" />
Nombre :<input type="text" name="t2" />

Registrar : <button type="submit" name="reg" value="registrar" > </button>

<?
If(isset(reg).....

Valida campos 
....

?>
    
asked by PieroDev 18.01.2018 в 05:12
source

1 answer

1

The way to make a request without reloading the whole page is to use AJAX

There is the form with pure javascript with XMLHttpRequest or at my very personal opinion the most simple that is using $.ajax() in this way

var request = $.ajax({
    dataType: 'json',
    method: 'POST',
    url: '/path/a/tu-url.php',
    data: $( "form" ).serialize()
});

//Manejo cuando la petición termina
request.done(function( event ) {
    // Aquí puedes redirigir si no hay fallos
});

//Manejo cuando la petición falla
request.fail(function( jqXHR, textStatus ) {
    alert( "Request failed: " + textStatus );
});

Or even simpler with $ .post () in this way

$.post( "/path/a/tu-url.php", $( "form" ).serialize());

Here is a functional example of how an AJAX execution of a form works

$('form').submit(function(e) {
  e.preventDefault()

  $('.invalid-helper').remove();

  var validates = true;
  var $inputs = $(this).children('input');

  $.each($inputs, function() {
    // Revisamos que los campos no estén vacíos
    if ($(this).val() === '') {
      validates = false;
      $(this).after('<span class="invalid-helper">El campo no puede estar vacío</span>');
    }
  });

  if (!validates) {
    return;
  }

  $.post(
      "https://hookb.in/vaP3LY5a",
      $("form").serialize()
    ).done(function() {
      console.log('Éxito');
    })
    .fail(function() {
      console.log('Falló');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form" action="https://requestb.in/y6crnty6" method="post">
  <input type="text" name="input_1">
  <br/>
  <input type="text" name="input_1">
  <br/>
  <input type="text" name="input_1">
  <br/>
  <button type="submit">Enviar</button>
</form>

I hope I have been helpful, if you do not leave me a comment:)

    
answered by 18.01.2018 / 05:48
source