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

Asked

Viewed 1,009 times

1

Good night, you guys!

I am having a problem with my application. The problem is this, I have a form to log in and a button like submit, when I click this button, the form is submitted to validate and verify the login, but then, after validating it I would like the div updated with the user name.

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

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="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’d like to div press 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. From now on, thank you >.<

  • A session is started by the session_start() function, to be placed at the top of the page, before any other code. You are using this function on your pages?

  • Yes I am in the file verificaSessao.php of my include

  • Why don’t you just do Ubmit by ajax? so you will send the Ubmit and give the return in php if it is successful you do an action in javascript and if it is not do another... ai inside this javascript you would do the Insert of this div

  • I saw that one submit uses the method GET and as I’m handling password I think the right thing would be to deal with POST No? You can make use of this method via Ajax?

1 answer

1


To capture the data, validate and return a reply without refreshing the page, only making an asynchronous request.

There is a javascript plugin called jQuery Form. It has two methods called: ajaxForm and ajaxSubmit. To solve your case, I advise the 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 Obs.: The method ajaxSubmit already captures the action="" and the method="" of <form>. But if you want to change without being in the uncomplicated form 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

  • Thank you, it will work perfectly

Browser other questions tagged

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