1
Well guys, I’m having a really hard time validating this page in ajax, I think the problem is in the php connection file, I searched in numerous Formularios but I didn’t want something so complex or with so many validations, just something simple, I’ll post the files, when I click in it keeps taking me to php page, instead of doing everything in the background without reloading, and error/success messages also do not appear in div "#error".
login js.
$('document').ready(function(){
$("#entrar").click(function(){
var data = $("#form").serialize();
$.ajax({
type : 'POST',
url : 'login.php',
data : data,
dataType: 'json',
beforeSend: function()
{
$("#entrar").html('Validando ...');
},
success:function(response){
if(response.codigo == "1"){
$("#entrar").html('Entrar');
$("#error").html('ACESSO PERMITIDO')
setTimeout(' window.location.href = "index.php"; ',4000);
}
else{
$("#entrar").html('Entrar');
$("#error").html('<strong>Usuario e/ou senha incorreto </strong>');
}
}
});
});
});
<html>
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="login.js"></script>
<body>
<div id="error"></div>
<form id="form" method="post" action="login.php">
<center> <input class=borda name="login" type="text" required="true" class="form-group" id="login" placeholder="Usuário" title="Informe o usuário."/></center>
<br>
<center><input class=borda name="senha" type="password" id="senha" class="txt-form-control" placeholder="*****" required="true" title="Informe a senha."></center>
<center>
<p>
<input type="submit" name="entrar" id="entrar" onclick="" value="ENTRAR">
</p>
<p><a href="cadastro.php">Cadastre-se</a> </p>
</center>
</form>
</body>
</html>
<?php
$login = $_POST['login'];
$entrar = $_POST['entrar'];
$senha = md5($_POST['senha']);
$connect = mysql_connect('localhost','root','root', 'db_test');
$db = mysql_select_db('db_test');
if (isset($entrar)) {
//Consulta no banco de dados
$sql="select * from usuario where login='".$login."' and senha='".$senha."'";
$resultados = mysql_query($sql)or die (mysql_error());
$res=mysql_fetch_array($resultados);
// Se login e senha estiverem certos
if (@mysql_num_rows($resultados) !== 0){
$retorno = array('codigo' => '1');
if(!isset($_SESSION))
session_start();
header("Location: success.php");
$_SESSION['nomeUsuario']=$res['login'];
echo json_encode($retorno);
}else{
$retorno = array('codigo' => '0');
echo json_encode($retorno);
exit();
exit;
}
}
?>
Already tried using Event.preventDefault() ?
– Johnny Gabriel