I am practicing PHP POO with javascript and ajax, I have my code ready with the sql query:
public function SessionStart() {
$conexion = $this->conectar();
$sql = "SELECT * FROM usuarios WHERE usuario = ? AND pass = ?";
$consulta_preparada = $conexion->prepare($sql);
$consulta_preparada->execute(array($this->nombre, $this->pass));
//rowCount devuelve el numero de filas con las que ha coincidido, 1 o 0
$login = $consulta_preparada->rowCount();
if ($login > 0) {
session_start();
$datos = new stdClass();
$datos->usuario = "Shum";
$datos->edad = "18";
$this->json= json_encode($datos);
}else {
$this->json = 0;
}
}
json is a global variable, and if the query is successful I create an array by saving the data in it and then in the variable json.
This is returned using the getJson method:
public function getJson() {
return $this->json;
}
here my code JS:
$("#php").submit(function () {
//empaquetamos las variables
usuario = $(".usuario").val();
pass = $(".pass").val();
if (usuario === "" || pass === " ") {
alert("Datos incorrectos");
}else {
var usuario_pass = {
usuario:$(".usuario").val(),
pass:$(".pass").val()
}
//los pasamos por post a la pagina
$.post("Login_variables.php", usuario_pass, login);
}
//con esto la pagina no se actualiza al presionar submit
return false;
});
function login (json) {
var jSON = $.parseJSON(json);
if (jSON.usuario != 0) {
$("#acceso").innerHTML = " ";
$("#acceso").text("Acceso permitido");
alert;
}else {
$("#acceso").innerHTML = " ";
$("#acceso").text("Acceso denegado");
}
}
As you can see in the ajax part, I pass the variables to the page Login_varibles.php, where I will leave the code:
<?php
require ("Conexion.php");
require ("Login.php");
$login = new login();
$login->SessionStart();
echo $json = $login->getJson();
? >
everything ready, I create a new instance which will take care of the sentence and once finished I call the getJson method to return the Json, but when it comes to accessing the values from php, I get undefined, so I do: 'function login (json) {
if (jSON.usuario != 0) {
$("#acceso").innerHTML = " ";
$("#acceso").text("Acceso permitido");
alert(jSON.usuario);
}else {
$("#acceso").innerHTML = " ";
$("#acceso").text("Acceso denegado");
}
}
I do not know why, if someone could help me I would appreciate it:)