-1

When I try to get a Session variable into a php script called with AJAX to make a MySQL query it gives me ""

I've tried passing the id using a hidden_input filled with php at the loading of my web page and the function worked! but when I try to catch the session variable directly from the script called by the AJAX it stops working again :(

This is the code where I set my php variables, I call this script directly from a html form.

<?php

    if(isset($_POST['empresa']))
    {
        if(isset($_POST['usuario']))
        {
            if(isset($_POST['password']))
            {

                $empresa = $_POST["empresa"];
                $usuario = $_POST["usuario"];
                $password = $_POST["password"];

                $host = "localhost";
                $bd = "nominet_Directorio_Web_Beta";
                $us = "nominet_Marvin2";
                $pas = "NominetBD2019!";

                error_reporting(0);

                $con = new mysqli($host, $us, $pas, $bd);

                if($con->connect_errno)
                {
                    echo "Error de conexión al servidor de base de datos...";
                    exit(); 
                }

                mysqli_set_charset('utf8');

                $query = "SELECT `Tbl_Usuarios`.`Id`, `Tbl_Usuarios`.`Fk_Empresa`, `Tbl_Usuarios`.`Tipo_Usuario` FROM `Tbl_Usuarios` INNER JOIN `Tbl_Empresas` ON `Tbl_Usuarios`.`Fk_Empresa` = `Tbl_Empresas`.`Id` WHERE `Tbl_Usuarios`.`Usuario` = '" . $usuario . "' AND `Tbl_Usuarios`.`Password` = '" . $password . "' AND `Tbl_Empresas`.`Razon_Social` = '" . $empresa . "'";
                //$query = "SELECT `Tbl_Administradores`.`Id` FROM `Tbl_Administradores` WHERE `Tbl_Administradores`.`Usuario` = '" . $usuario . "' AND `Tbl_Administradores`.`Password` = '" . $password . "'";

                $resultado = mysqli_query($con, $query);
                $res= mysqli_fetch_array($resultado);

                if($res["Id"] > 0)
                {

                    session_start();

                    $_SESSION["Id"] = $res["Id"];
                    $_SESSION["Empresa"] = $res["Fk_Empresa"];
                    $_SESSION["Usuario"] = $usuario;
                    $_SESSION["Tipo_Usuario"] = $res["Tipo_Usuario"];

                    header("Location: ../SISTEMA/");
                }
                else
                {
                    header("Location: ../?error=0");
                }

            }
            else
            {
                header("Location: ../?resp=error1");
            }

        }
        else
        {
            header("Location: ../?error=2");
        }
    }
    else
    {
        header("Location: ../?error=3");
    }
?>

The code below it's my JavaSCript (JQuery) function where I call my php script.

function contactosGeneral(){

    //var empresa = $('#hidden1').val();
    var funcion = "contactosGeneral";

     $.ajax({
        url: "/PHP/PRUEBA.PHP",
        type: "POST",
        data: {funcion: funcion},
        error: function(xhr){
            window.location.href = "../REPORTES/?resp=0";
        },
        success: function(respuesta) {

            var arreglo = JSON.parse(respuesta);

           $('#p_contactos').html(arreglo[0]["resp"]);

        }
    });

}

this is my php script, here I call the DataBase.

<?php

    $funcion = $_POST['funcion'];

    switch($funcion){
        case 'contactosGeneral':
            break;
    }

    function contactosGeneral(){
        require("../../ABRIR_CON.php");

        //$empresa = $_POST['empresa'];

        session_start();

        $empresa = $_SESSION["Empresa"];

        $sql = 'SELECT COUNT(`Tbl_Contactos`.`Id`) AS "resp" FROM `Tbl_Contactos` WHERE `Tbl_Contactos`.`Fk_Empresa` = ' . $empresa;

        $query = mysqli_query($con, $sql);

        $json = array();

        while($row = mysqli_fetch_array($query))     
        {

            $json[]=array('resp'=>$row['resp']);
        }


        $resources_JSON_array = json_encode($json);
        echo $resources_JSON_array;

        require("../../CERRAR_CON.php");
    }

?>

I know there's a lot I can improve in my code, but i'm not here for that reason, just help my with my question. thanks :)

  • 1
    You never call `contactosGeneral()` in the PHP script. You need to put that in `case 'contactosGeneral':` – Barmar Jun 18 '19 at 21:02
  • 1
    FYI, you can use `$json[] = $row;`, you don't need to make a new array. – Barmar Jun 18 '19 at 21:04
  • 1
    There's also no need for a `while` loop, since the query only returns 1 row. – Barmar Jun 18 '19 at 21:04
  • 2
    `session_start();` should be first line after ` – bakero98 Jun 18 '19 at 21:09
  • @Barmar you're right, I never called my php function, Thank you a lot!!! – Marvin García Jun 18 '19 at 21:22
  • 1
    @MarvinGarcía add session start in your script ( the one you call the database) also always validate the session like this example https://stackoverflow.com/questions/6249707/check-if-php-session-has-already-started otherwise return a forbidden content – stan chacon Jun 19 '19 at 22:39

1 Answers1

0

As @Barman said, I never called my php function contactosGeneral() into my switch(){} code :B