How to receive data from php to ajax?

1

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:)

    
asked by Shum 02.07.2018 в 05:47
source

1 answer

0

I have another way to implement it with ajax , I hope and it will be useful and you can implement it to your project, I will tell you the code so that you have an idea of how it does it, example:

$this->json= json_encode($datos);//En lugar de esto
echo json_encode($datos);//cambialo por esto
/*
----------------------------------
----------------------------------
*/

$('#btnEnviar').click(function(){//Puedes uarlo como submit o click, como se te haga mejor

    var v_usuario = $(".usuario").val();
    var v_pass = $(".pass").val();

    if(v_usuario != "" && v_pass != ""){

         $.ajax({
         url: 'Login_variables.php',//El archivo .php que recibirá los parámetros, pon bien la ruta.
         type: 'GET',//El método para obtener los datos
         dataType: 'json',//Le dices que recibirás como respuesta un json
         data: {usuario: v_usuario, pass: v_pass},//le mandas los parámetros
         }).done(function(data){//El data recibirá el json_encode

         /*Depende de lo que le asignes despues de '$datos->', es lo que recibirá el data 
           $datos->usuario = "Shum";
           $datos->edad = "18";
         */
         if(data.usuario != "" && data.edad != ""){
          //si lo que te devuelva la consulta en el data son diferentes de vacío, quiere decir que sí encontró al usuario. 
           alert('Acceso correcto');
         }else{
           alert('Acceso incorrecto');
         }

        });
    }       
 });
    
answered by 02.07.2018 в 07:56