Sending a form without reloading the page

1

I have a form ready and working normal. But what I need to do is this.

When I submit the form it will not refresh the page and returns me

"Successfully signed in" or "Nick already exists", "Invalid email"

<form class="form3" action="" method="POST" enctype="multipart/form-data">
    <p>Nome completo</p>
    <input type="text" class="Nome" name="Nome" placeholder="Nome completo *">

    <p>Nome de usuário</p>
    <input type="text" name="Nick" placeholder="Nick da conta *">

    <p>E-mail</p>
    <input type="text" name="Email" placeholder="Informe seu E-mail *">

    <p>Senha</p>
    <input type="password" name="Senha" placeholder="Informe a sua senha *">

    <input type="submit" id="Bot_login" name="Cadastra" value="Criar conta">
</form>

<?php
    if(isset($_POST['Cadastrar'])){
        $Nome       = htmlspecialchars($_POST['Nome'],ENT_QUOTES);
        $Nick       = htmlspecialchars(trim($_POST['Nick']),ENT_QUOTES);
        $Email      = htmlspecialchars(trim($_POST['Email']),ENT_QUOTES);
        $Senha      = htmlspecialchars(trim($_POST['Senha']),ENT_QUOTES);

        if($Nome == ""){
            echo 'Preencha o campo Nome corretamente!';
        }
        if($Nick == ""){
            echo 'Preencha o campo Nick corretamente!';
        }
        if($Email == ""){
            echo 'Preencha o campo E-mail corretamente!';
        }
        if($Senha == ""){
            echo 'Preencha o campo Senha corretamente!';
        }
        else{
            $SQL_Cadastro = mysqli_query($conex,"INSERT INTO UserLog (Nome, Nick, Email, Senha) VALUES ('$Nome', '$Nick', '$Email', '$Senha')");
        }
    }
    else{

    }
?>
    
asked by anonymous 26.02.2018 / 18:32

2 answers

4

Use jQuery.ajax , jQuery.post , XMLHttpRequest or Fetch for this functionality.

jQuery.Ajax

jQuery.Ajax is a function based on XMLHttpRequest . It is for sending requests of type GET, POST, PUT, DELETE etc.

With these requests you can also send and receive data. In the case of jQuery.ajax , just enter in the data property, which data you want to send.

To capture the return, there are three functions that can be used for this: success for when there are successes in the requisitions; error for when there is an error; and complete for when the request is completed.

In our example, I'll only use the success function, but it's up to you to use the others as well.

Example:

$("#Bot_login").click( function(event) {

    event.preventDefault();

    $.ajax({
      /* URL da requisição */
      url: 'sua-url',

      /* Tipo da Requisição */
      type: 'POST',

      /* Campos que serão enviados */
      data: {
        Nome: $('input[name="Nome"]').val(),
        Nick: $('input[name="Nick"]').val(),
        Email: $('input[name="Email"]').val(),
        Senha: $('input[name="Senha"]').val()
      },

      /* Os campos abaixo são necessários quando há envio de arquivos */
      processData: false,
      cache: false,

      /* Função para quando houver sucesso na requisição */
      success: function( response ) {
        alert( response );
      }
    });

});

XMLHttpRequest

XMLHttpRequest is the basis of jQuery.Ajax and jQuery.Post . It works the same way, however, with methods and form of submission a little different.

  

XMLHttpRequest is an API that provides functionality to the client to transfer data between a client and a server. It provides an easy way to retrieve data from a URL without having to do a full page update.

In programming, this is called Ajax = Asynchronous JavaScript and XML. Apesr's name does not necessarily have to be in XML.

Example:

/**
 * Cria uma requisição e adiciona um evento
 * quando quando a requisição for finalizada
 */
const xhr = new XMLHttpRequest();
xhr.addEventListener("loaded", response => {
  alert( response.target.success );
});

$("#Bot_login").click(function(event) {

  event.preventDefault();

  /* Abre uma requisição do tipo POST */
  xhr.open("POST", "sua-url", true);

  /* Envia a requisição */
  xhr.send( new FormData( document.querySelector("form") ) )

});

Fetch

Fetch is an alternative version of XMLHttpRequest , but it - promises - a set of features that make it more "powerful" and flexible than XHR

This function works with generic objects of type Request and Response . It is ideal for anyone who wants to work with Service Work , cache manipulation through Cache API , requests etc.

It only has one parameter. In this parameter you can pass a "string" (URL) or a Request object with the settings of your request.

Example:

$("#Bot_login").click(function(event) {

  event.preventDefault();

  /* Cria uma requisiçãod o tipo POST */
  const request = new Request("sua-url", {
    method: "POST",
    body: new FormData( document.querySelector("form") )
  });

  /* Executa a requisição e retorna o resultado */
  fetch(request).then( response => {
    return response.text(); // ou return response.json();
  } )
  .then ( result => {
    alert( result );
  });

});

jQuery.Post

This is an alternative, compact version of jQuery.Ajax

$.post('sua-url', {
        Nome: $('input[name="Nome"]').val(),
        Nick: $('input[name="Nick"]').val(),
        Email: $('input[name="Email"]').val(),
        Senha: $('input[name="Senha"]').val()
}, function(response) {
  alert( response )
})
    
26.02.2018 / 18:47
-1

Good morning uses the global variables to display the messages on the same page. follows changed code.

<form class="form3" action="" method="POST" enctype="multipart/form-data">
<?php
if(isset($_SESSION['msg']):
echo $_SESSION['msg'];
unset($_SESSION['msg'];
endif;
?>

<p>Nome completo</p>
<input type="text" class="Nome" name="Nome" placeholder="Nome completo *">

<p>Nome de usuário</p>
<input type="text" name="Nick" placeholder="Nick da conta *">

<p>E-mail</p>
<input type="text" name="Email" placeholder="Informe seu E-mail *">

<p>Senha</p>
<input type="password" name="Senha" placeholder="Informe a sua senha *">

<input type="submit" id="Bot_login" name="Cadastra" value="Criar conta">
</form>

<?php
    if(isset($_POST['Cadastrar'])){
        $Nome       = htmlspecialchars($_POST['Nome'],ENT_QUOTES);
        $Nick       = htmlspecialchars(trim($_POST['Nick']),ENT_QUOTES);
        $Email      = htmlspecialchars(trim($_POST['Email']),ENT_QUOTES);
        $Senha      = htmlspecialchars(trim($_POST['Senha']),ENT_QUOTES);

        if($Nome == ""){
            $_SESSION['msg'] = 'Preencha o campo Nome corretamente!';
        }
        if($Nick == ""){
            $_SESSION['msg'] = 'Preencha o campo Nick corretamente!';
        }
        if($Email == ""){
            $_SESSION['msg'] = 'Preencha o campo E-mail corretamente!';
        }
        if($Senha == ""){
            $_SESSION['msg'] = 'Preencha o campo Senha corretamente!';
        }
        else{
            $SQL_Cadastro = mysqli_query($conex,"INSERT INTO UserLog (Nome, 
Nick, Email, Senha) VALUES ('$Nome', '$Nick', '$Email', '$Senha')");
    $_SESSION['msg'] = "Usuario Cadastrado com sucesso";
        }
    }
    else{
     $_SESSION['msg'] = "Erro ao cadastrar usuario";
    }
?>

So echo $ _SESSION will be responsible for displaying each message defined and will destroy soon after the message disappears when the page is updated, the page must be updated to capture the data after it will define the message in the global variable and shows it according to the result, is a simple way without using JS, angular or any other technology.

I hope to have helped start now in the development field.

    
26.02.2018 / 18:50