You still need to link the JS function to the form.
<form id="login-form" class="signup-form" action="logearse.php" method="POST" onsubmit="submitForm()">
Here are a couple of things you have to evaluate, or send the information by FORM
or send it by AJAX
As you are doing these combining the two and you will never have the result you want
If it is by FORM
, then it has nothing to do here AJAX
, do not invoke the function, so PHP will correctly return the redirection headers with their respective variables.
Let's solve it first by FORM
, you still have to add some instructions in PHP to see the errors. I'll place it in the error div
<div id="error">
<?php
if( !empty($_GET['error']) ){
echo 'Hubo un error: <b>' . $_GET['error'] . '</b>';
}
if( !empty($_GET['login']) ){
echo 'Te logueaste correctamente: <b>' . $_GET['login'] . '</b>';
}
?>
</div>
Now for it to work we must modify a little the headers that you return in PHP, these two to be specific:
header ("Location: index.php?error=userorpwdincorrect");
header ("Location: index.php?error=empty");
header ("Location: index.php?login=success");
This does, when the browser returns an error, the PHP of your login.php
and the instructions are inside the DIV of the error, validate if there is a variable in the URL that is called error, if there is then the we render
I did the same when the connection is successful, that in terms of technique is everything, remember to erase your JS because with this technique it will no longer serve you. (At the moment, you can do great things, but you need to fall)
Let's review what you are doing now with AJAX. As a recommendation (And by the same acronym of AJAX) it is recommended to use JSON o XML
as a response type, you can not return a header to AJAX because it does not expect a header, we will correct it.
First, you must cut the button's native functionality when sending.
<script>
//Cuando esté listo el DOM
$(function(){
//Detectar cuando se da click al botón de login
$(document).on('click','#login-button',function(e){
//Cortar funcionalidad
e.preventDefault();
//Declaramos el objeto que enviaremos por AJAX
//y le ponemos sus valores, recuerda que JSON trabaja bajo clave->valor
var obj = {
'nick': $('#nick').val().trim(),
'pwd': $('#pwd').val().trim(),
};
//Ahora si invocamos a AJAX
$.ajax({
url:'loguearse.php',
method:'POST',
data: obj,
success:function( respuesta ){
//Vemos que trae el nodo de respuesta
alert( respuesta.mensaje );
},
error: function( e, err, error ){
//Añadimos un nodo de error, por si pasa algo en el servidor, esto lo vamos a ver en la consola de depuración
console.log(e, err, error);
}
})
});
})
</script>
Now, we are going to change the answers of your file loguearse.php
You have errors in the logic of the structure, so I will straighten it a bit, I leave you comments:
<?php
session_start();
include_once 'conexion.php';
//Declaramos un arreglo que será nuestro retorno
$respuesta = array();
//Primero hay que validar que las variables existan
//La superglobal $_REQUEST responde a los verbos GET y POST
if( empty( $_REQUEST['pwd'] ) || empty( $_REQUEST['nick'] ) ){
$respuesta['mensaje'] = 'Usuario y/o password vacío';
}
else{
//Guardamos y limpiamos las variables
$pwd= mysqli_real_escape_string($conn, $_REQUEST ['pwd']);
$nick= mysqli_real_escape_string($conn, $_REQUEST ['nick']);
//Creamos el SQL, no siempre funciona agregando así las variables, yo recomiendo concatenar
$sql = "SELECT * FROM Usuario WHERE nick = '". $nick. "' AND password = '".$pwd ."'";
//Validamos que la consulta esté bien hecha
if( !$result = mysqli_query ($conn, $sql) ){
$respuesta['mensaje'] = 'Tronó la consulta';
}
else{
//Aquí asignamos nuestro arreglo, assoc o array te sirven
$row = mysqli_fetch_array( $result );
//creas tus variables de sesión
$_SESSION['id'] = $row['id'];
$_SESSION['nick'] = $row['nick'];
$respuesta['mensaje'] = 'Se crearon las variables de sesión, conexión exitosa';
//Recuerda que por limpieza del servidor, borramos la información de la query y cerramos conexión
mysqli_free_result($result);
mysqli_close( $conn );
}
}
//Ahora si, retornamos nuestra respuesta con formato y encabezado JSON
header('Content-Type: application/json');
echo json_encode($respuesta);
?>
This is how an AJAX behaves, maybe there are a couple of errors, I have no environment to test, but it will not be a problem for you.
Lastly and as a recommendation, you have serious security holes in passwords, take a look at Password Hash so you can see how you solve it.
Annex clarification of associative arrays in PHP and objects in Javascript
An associative arrangement is also known as a two-dimensional or multidimensional arrangement, I exemplify
This would be a common arrangement in PHP
$arreglo = array('Moto','Carro','Bicicleta');
If you cycle the arrangement you will get each of the elements of the arrangement
foreach( $arreglo as $vehiculo ){
echo $vehiculo;
}
But how would you add planes to the same arrangement? Logic tells us
$arreglo = array('Moto','Carro','Bicicleta', 'Avión', 'Cohete', 'Hércules');
How do you know which is which? You do not know (Well yeah, you have to put a complex of regular expressions but that's not the case)
Then we start an associative arrangement with two dimensions, vehicles and airplanes, you would stay like this.
$arreglo = array();
$arreglo['vehiculos'] = array('Moto','Carro','Bicicleta');
$arreglo['aviones'] = array('Avión','Cohete','Hércules');
Now you can identify why each one belongs to a 'node'
foreach( $arreglo['vehiculos'] as $vehiculo){
echo $vehiculo;
}
foreach( $arreglo['aviones'] as $avion){
echo $avion;
}
When you return to Javascript with the JSON header and format, Javascript interprets them in the same way
success:function( respuesta ){
respuesta.vehiculos.forEach( function( vehiculo ){
console.log( vehiculo );
})
respuesta.aviones.forEach( function( avion ){
console.log( avion );
})
//también puede ser respuesta['aviones'] y respuesta['vehiculos']
}
And this is how PHP and Javascript maintain a synergy by speaking both the same "language"
It does not hurt that you continue to feed on PHP Associative Arrangements and JSON
JSON and XML is very fashionable, because it is fast and light, understanding this, you can enter the world of NodeJS and MongoDB if you want.
I hope you serve, greetings