How to submit a form and after submission load a div with ajax

1

Good evening, everyone!

I'm having a problem with my application. The problem is as follows, I have a form to login and a button of type submit , when I click on this button, the form is submitted to validate and verify the login, but then, after validating I would like div update with the user name.

Here is my visual page code, where is my form and my function that would respectively update the div

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script><scripttype="text/javascript">
$(document).ready(function(){
        $("#menu #formLogin").submit(function(e){
    e.preventDefault();
    var href = "../View/dropdown.php";
    $("#dropdown").load(href + "#dropdown");
        });
});
</script>

<div class="dropdown" id="dropdown">
     <center> <li style="display: block; width: 100px; margin-right: 10px; margin-left: 40px;"><a style="color: #ccc; text-decoration: none;" href="#"> <img src="../images/user.png" width="35px"><br> Minha conta  </a></li> </center>
     <div class="dropdown-content">
         <form name="formLogin" id="formLogin" action="../Controller/verificaLogin.php" method="post">
            <input style="width:250px;" type="email" id="userLogin" name="userLogin" placeholder="Digite seu email">
            <br>
            <input style="width:250px;" type="password" id="userPassword" name="userPassword" placeholder="Digite sua senha">
            <br>
            <input type="submit" value="Entrar" id="btnLogar" name="btnLogar" style="width: 100px;" >
            <a name="recuperaSenha" id="recuperaSenha" href="#"> Esqueci minha senha </a>
            <br> <br>
            <p style="color: #777"> Ainda não pussui conta? <a style="text-decoration: underline;" name="Cadastro" id="Cadastro" href="cadCliente.php"> Cadastre-se </a> </p>
        </form>
     </div>
  </div>

Here is the code that checks the login

include '../Model/conectaBanco.php'; 
include '../Model/clienteVO.php';
include '../Model/loginDAO.php';
include 'verificaSessao.php';

$cliente = new clienteVO();
$loginDAO = new loginDAO;
$mysqli = new mysqli("localhost", "root", "", "bdAliSantos");


if(NULL !== filter_input(INPUT_POST, "btnLogar")){
    $cliente ->setEmailLogin(filter_input(INPUT_POST, "userLogin"));
    $cliente ->setSenhaLogin(filter_input(INPUT_POST, "userPassword"));
    $senhaVerificar = $cliente->getSenhaLogin();

    if(!$cliente ->getEmailLogin() || !$cliente->getSenhaLogin()){
        echo "<script> alert('Por favor, verifique se digitou seu email e/ou senha corretamente'); document.location.href = '../View/index.php'; </script>";
    } else { 
        $nomeCliente = $loginDAO ->selecionaNome($cliente);
        $senhaCliente = $loginDAO ->selecionaSenha($cliente);
        if(($nomeCliente && $senhaCliente) && ($senhaCliente === $senhaVerificar)){
            if($cliente->getEmailLogin()=== "[email protected]"){
                $_SESSION['nomeUsuario'] = "Admin";
                $_SESSION['senhaUsuario'] = $senhaCliente;
                header("Location: ../View/indexAdm.php");
            }else{
                $_SESSION['nomeUsuario'] = $nomeCliente;
                $_SESSION['senhaUsuario'] = $senhaCliente;
                header("Location: ../View/index.php");
            }
        }
        else{
            header("Location: ../View/index.php");
        }   
    }                
}

And this is the code I would like div to load after submission

<div class="dropdown" id="dropdown">
<center> <li style="display: block; width: 100px; margin-right: 10px; margin-left: 40px;"><a style="color: #ccc; text-decoration: none;" href="#"> <img src="../images/user.png" width="35px"><br> <?php echo $_SESSION['nomeUsuario']; ?></a></li> </center>
<div class="dropdown-content"  style="padding: 0">
    <ul style="list-style-type: none; margin: 0; width: 200px; padding: 0;">
        <li><a href="../View/minhaConta.php" style="color: #777;"> Minha Conta </a></li>
        <li><a href="#" style="color: #777;"> Meus Pedidos </a></li>
        <li><a href="../View/minhasConfiguracoes.php" style="color: #777;"> Configurações </a></li>
        <li><a href="../Controller/sair.php" style="color: #777;"> Sair </a></li>
    </ul>
</div>

That's it .. Right now, thank you.

    
asked by anonymous 19.07.2017 / 03:00

1 answer

1

To capture the data, validate and return a response without updating the page, just by making an asynchronous request.

There is a javascript plugin called jQuery Form . It has two methods called: ajaxForm and ajaxSubmit . To resolve your case, I advise ajaxSubmit .

To use it is very simple:

Basic example of <form>

<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
    First Name: <input type="text" name="fname" value =""/> <br/>
    Last Name: <input type="text" name="lname" value ="" /> <br/>
    Email : <input type="text" name="email" value=""/> <br/>
</form>
<div id="resposta"></div>

Example Javascript Note: The ajaxSubmit method already captures action="" and method="" of <form> . But if you want to change the options: url and type of var options .

// prepare the form when the DOM is ready 
$(document).ready(function() { 
    var options = { 
        target:        '#resposta',   // div que irá receber a resposta 
        beforeSubmit:  valida,  // pre-submit callback 
        success:       responde  // post-submit callback 
        clearForm: true        // limpa os campos do form após submit 
        resetForm: true        // limpa os campos do form antes submit
        //url:       url         // sobreescreve o action do form 
        //type:      type        // sobreescreve o método 'get' or 'post'
    }; 

    // Aplica o evento de submit do form 
    $('#ajaxform').submit(function() {
        // aplica as configurações do options ao ajaxSubmit
        $(this).ajaxSubmit(options); 

        // !!! Importante !!! 
        // sempre retornar false para evitar o carregamento da página. Por baixo dos panos ele aplica 'event.preventDefault()'.
        return false; 
    }); 
});

// pre-submit callback 
function valida(formData, jqForm, options) { 
    // Aplique as validações do form aqui  
    // O return false previne o submit do form
    // Qualquer retorno ao contrário de false permitirá o submit do form 
    return true; 
} 

// post-submit callback 
function responde(responseText, statusText, xhr, $form)  { 
    //aplique as resposta ao usuário aqui
} 

Other examples

19.07.2017 / 14:27