Sending form without reloading page

Asked

Viewed 278 times

1

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

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

"Successfully registered" or Some error "Nick already exists", "Invalid e-mail"

<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{

    }
?>

2 answers

4


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


jQuery.Ajax

The jQuery.Ajax is a function based on XMLHttpRequest. It is used for sending requests like GET, POST, PUT, DELETE etc.

With these requests you can also send and receive data. In the case of jQuery.ajax, just inform at the property data, what data you want to send.

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

In our example, I will use only the function success, but it is 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

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

XMLHttpRequest is a API which provides functionality to the client to transfer data between a client and a server. It provides an easy way to recover 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 need to - necessarily - 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

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

This function works with generic objects of the type Request and Response. It is ideal for those who want to work with Service Work, cache handling via Cache API, requisitions etc.

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

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 and 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 )
})

-1

Good day uses the global variables to display messages on the same page. follows modified 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 the echo $_SESSION will be in charge of showing each defined message and destroy right up for the message to disappear when the page is updated, the page should be updated to capture the data after that it will set the message in the global variable and shows itla as the result, it is a simple way without using JS, angular or any other technology.

I hope I helped started now in the development business.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.