AJAX does not update div by id

Asked

Viewed 53 times

0

I am developing a login system, where I need to return the validation message to the user in a div on the login page itself, however the error message is appearing on the validation page. I’m using Bootstrap and PHP with PDO.

Login.php:

<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, user-scalable=no" />



        <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">


        <title>Login</title>
    </head>
<body>

<form id="loginform"  role="form" action="validaLogin.php" method="POST">

    <div class="form-group has-feedback">
               <label for="login" class="control-label">Login</label>

               <input type="text" 

               class="form-control" 
               id="inputLogin" 
               name="login" 
               placeholder="Insira seu login" 
               title="Insira seu Login" 
               required>

               <span class="glyphicon form-control-feedback" aria-hidden="true"></span>



          </div>

    <div class="form-group has-feedback">
               <label for="inputSenha" class="control-label">Senha</label>

               <input type="password" 

               class="form-control" 
               id="inputSenha" 
               name="senha" 
               placeholder="Insira sua senha" 
               title="Insira sua Senha" 
               required>

               <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
               <div class="help-block with-errors" id="login-alert"><span id="mensagem"></span></div>
    </div> 



    <div class="form-group margin-top-pq">
        <div class="col-sm-12 controls">
            <button type="submit" class="btn btn-primary" name="btn-login" id="btn-login">
              Entrar
            </button>
        </div>
    </div> 


</form>
<script type="text/javascript" src="bower_components/jquery/dist/jquery.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="check.js"></script>
</body>
</html>

check js.:

The code below should return an error message in the div #message

<script >$('document').ready(function(){

  $("#btn-login").click(function(){
    var data = $("#loginform").serialize();

    $.ajax({
      type : 'POST',
      url  : 'Login.php',
      data : data,
      dataType: 'json',
      beforeSend: function()
      { 
        $("#btn-login").html('Validando ...');
      },
      success :  function(response){            
        if(response.codigo == "1"){ 
          $("#btn-login").html('Entrar');
          $("#login-alert").css('display', 'none')
          window.location.href = "selectPersonagem.php";
        }
        else if(response.codigo == "0"){     
          $("#btn-login").html('Entrar');
          $("#login-alert").css('display', 'block');
          $("#mensagem").html('<strong>Erro! </strong>' + response.mensagem);
        }
        }
    });
  });

});

validaLogin.php

On this page I do the server side validation, blocking the ID after 5 error attempts, everything works, but instead of showing the error message on the login page, the error message appears on itself valida.php in this way:

{codigo":"0","mensagem":"Usu\u00e1rio n\u00e3o autorizado, voc\u00ea tem mais 4 tentativa(s) antes do bloqueio!"}

In other words, it returns the JSON, but in check.js it does not access its information.

This is one of the snippets of code that should return the message:

<?php
session_start();

// Constante com a quantidade de tentativas aceitas
define('TENTATIVAS_ACEITAS', 5); 

// Constante com a quantidade minutos para bloqueio
define('MINUTOS_BLOQUEIO', 30); 

// Require da classe de conexão
require 'conn.php';


// Dica 1 - Verifica se a origem da requisição é do mesmo domínio da aplicação
if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] != "http://localhost/loginphp/login.php"):
    $retorno = array('codigo' => 0, 'mensagem' => 'Origem da requisição não autorizada!');
    echo json_encode($retorno);
    exit();
endif;

I am starting in ajax and PHP, I removed this code from this tutorial: tutorial

  • How are you logging in? You send the POST to Login.php, but there is no login validation code.

  • It turns out you’re checking whether the value of código is equal to 1, but you do not return the value 1 in the archive validaLogin.php, you’re just returning the 0

  • @Valdeirpsr this is only part of the code of the page, it works correctly and returns the JSON with the answer, the problem is time to take the information in JSON and show in id.

  • Got it. But he’s returning JSON with the code 1 also? In your case, Javascript will not work because the user will be redirected by clicking the login button to avoid this add type="button" button and correct the URL in $.ajax({ ... })

  • Yes, it’s returning with 1 too.

  • In case when I put as Button on the type, it changes the text of the button but does not send to the validation page

  • when you put "1" the content becomes string and not integer, have you tried to remove the quotation marks? or try parseint(Answer.code)

Show 2 more comments
No answers

Browser other questions tagged

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