Sending external PHP variable to Javascript

Asked

Viewed 433 times

4

I need to receive a message sent from PHP, and I need to receive it on the screen, to warn if the login is correct or not. However I do not want to use ajax.

The code I’m getting in the internal script the index:

<script type="text/javascript">
    $('document').ready(function(){         
        if ($_SESSION['VALIDACAO'] == 01){
            var Texto = "Login inválido"
            document.getElementById("msg").innerHTML = Texto;
        }else{
            var Texto = "Úsuario bloqueado, contacte o administrador do sistema."
            document.getElementById("msg").innerHTML = Texto;
        };
    });
</script>

My php:

<?php


include ("../includes/conexao.php");

$email = ($_POST['TXT_ENDER_EMAIL']);
$senha = ($_POST['TXT_SENHA_USUAR']);

// Validação do usuário/senha digitados
$sql = "SELECT COD_IDENT_USUAR, TXT_NOMEX_USUAR, TXT_ENDER_EMAIL, FLG_STATU_USUAR FROM tbl_USUARIOS WHERE TXT_ENDER_EMAIL = '".$email."' AND TXT_SENHA_USUAR = '".$senha."'";
$qr = mysql_query($sql);
if (mysql_num_rows($qr) != 1) {
    // Mensagem de erro quando os dados são inválidos e/ou o usuário não foi encontrado
    $_SESSION['VALIDACAO'] = 01;
    header("Location: ../index.php"); exit; // Redireciona o visitante
} else {
    // Salva os dados encontados na variável $resultado
    $resultado = mysql_fetch_assoc($qr);


    // Se a sessão não existir, inicia uma
    if (!isset($_SESSION)) session_start();

    // Salva os dados encontrados na sessão
    $_SESSION['UsuarioID'] = $resultado['COD_IDENT_USUAR'];
    $_SESSION['UsuarioNome'] = $resultado['TXT_NOMEX_USUAR'];
    $_SESSION['UsuarioEmail'] = $resultado['TXT_ENDER_EMAIL'];
    $_SESSION['UsuarioFlag'] = $resultado['FLG_STATU_USUAR'];

    if($resultado['FLG_STATU_USUAR'] == 'A'){
    // Redireciona o visitante
    header("Location: ../paginas/principal.php"); exit;
    }else{
        session_destroy(); // Destrói a sessão limpando todos os valores salvos
        $_SESSION['VALIDACAO'] = 02;
        header("Location: ../index.php"); exit; // Redireciona o visitante

    }
}
?>

The new model is working as follows. index php.:

<!DOCTYPE html>
<?php include 'scripts/help.php'; 
?>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
    <title>JR Tela de login</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

    <!--<script src="js/principal01.js"></script>-->
</head>
<body>
    <div class="container">
        <form class="form-signin" id="from" name="form" method="POST" action="scripts/validacao.php">
            <h2 class="form-signin-heading">JR Comunicações</h2>

            <div id="msg"><?php get_msg('msg_login');?></div>

            <input type="text" name="TXT_ENDER_EMAIL" class="input-block-level" placeholder="Email">
            <input type="password" name="TXT_SENHA_USUAR" class="input-block-level" placeholder="Senha">
            <input class="btn btn-large btn-success" type="submit">
        </form>
    </div>

</body>
</html>

The help.php file:

<?php
// Função para setar a mensagem
function set_msg($id, $msg, $tipo)
{
    session_start();
    if (isset($id)) {
       $_SESSION['id'] = $id;
       switch ($tipo) {

        case 'error':
            $_SESSION['msg'] = '<div class="alert-danger">' . $msg . '</div>';
            break;

        case 'alert':
            $_SESSION['msg'] = '<div class="alert-alert">' . $msg . '</div>';
            break;
        }
    }
}

// Esta função vai exibir sua mensagem onde você quiser
function get_msg($id)
{
    session_start();
    if (isset($_SESSION['msg'])) { echo $_SESSION['msg']; }
    if (isset($id)) {
        if ($id == $_SESSION['id']) {
            echo $_SESSION['msg']; 
        }
    }
    return FALSE;
}

?>

and the validation.php:

<?php
include ("../includes/conexao.php");
include("help.php");

$email = ($_POST['TXT_ENDER_EMAIL']);
$senha = ($_POST['TXT_SENHA_USUAR']);

// Validação do usuário/senha digitados
$sql = "SELECT COD_IDENT_USUAR, TXT_NOMEX_USUAR, TXT_ENDER_EMAIL, FLG_STATU_USUAR FROM tbl_USUARIOS WHERE TXT_ENDER_EMAIL = '".$email."' AND TXT_SENHA_USUAR = '".$senha."'";
$qr = mysql_query($sql);
if (mysql_num_rows($qr) != 1) {
    // Mensagem de erro quando os dados são inválidos e/ou o usuário não foi encontrado
    set_msg('msg_login', 'Login ou senha inválidos', 'error');
    header("Location: ../index.php"); exit; // Redireciona o visitante
} else {
    // Salva os dados encontados na variável $resultado
    $resultado = mysql_fetch_assoc($qr);


    // Se a sessão não existir, inicia uma
    if (!isset($_SESSION)) session_start();

    // Salva os dados encontrados na sessão
    $_SESSION['UsuarioID'] = $resultado['COD_IDENT_USUAR'];
    $_SESSION['UsuarioNome'] = $resultado['TXT_NOMEX_USUAR'];
    $_SESSION['UsuarioEmail'] = $resultado['TXT_ENDER_EMAIL'];
    $_SESSION['UsuarioFlag'] = $resultado['FLG_STATU_USUAR'];

    if($resultado['FLG_STATU_USUAR'] == 'A'){
    // Redireciona o visitante
    header("Location: ../paginas/principal.php"); exit;
    }else{
        session_destroy(); // Destrói a sessão limpando todos os valores salvos
        set_msg('msg_login', 'Usuario bloqueado', 'error');
        header("Location: ../index.php"); exit; // Redireciona o visitante

    }
}
?>
  • The function get_msg() ta wrong friend: Does so: Function get_msg($id) { session_start(); if (isset($id) && $id == $_SESSION['id']) { if (isset($_SESSION['msg'])) { echo $_SESSION['msg']; Return FALSE; }

  • Still giving error, here the if (isset($id) && $id == $_SESSION['id']) {

  • at the beginning of the get_msg() function just after session_start(); Places this code: echo '<pre>'; print_r($_session); die; and places here what appears there.

  • Array ( [Usuarioid] => 1 [Usuarioname] => Renan Moraes [Usuarioemail] => [email protected] [Usuarioflag] => A )

  • You already have a session created from a session_destroy(); there to test.

  • did not work, error in this command.

  • What more correct method to solve this, I will have to give an exit 13:50 I return, I ask you to help me, it is for a work for college that I will have to deliver Saturday.

  • I returned managed to identify something ?

  • @Kayobruno is still not working its code. Error on the if line (isset($id) && $id == $_SESSION['id']) {

  • Debate on the relevant goal for this question: http://meta.pt.stackoverflow.com/q/3918/132

Show 5 more comments

3 answers

3

You’re not putting the tag php in the check you are doing

<script type="text/javascript">
    $('document').ready(function(){         
        <?php if ($_SESSION['VALIDACAO'] == 01){?>
            var Texto = "Login inválido"
            document.getElementById("msg").innerHTML = Texto;
        <?php }else{?>
            var Texto = "Úsuario bloqueado, contacte o administrador do sistema."
            document.getElementById("msg").innerHTML = Texto;
        <?php };?>
    });
</script>
  • Uncaught Syntaxerror: Unexpected token < Give this error, and in the PHP log it says that the variable has not been set

  • Which variable was not defined?

2


I think you don’t need to use javascript or jquery, as you don’t want to use Ajax you can only use PHP itself. Create a "helper" file that will contain auxiliary functions and do the following functions:

// Função para setar a mensagem
public function set_msg($id, $msg, $tipo)
{
    if (isset($id)) {
       $_SESSION['id'] = $id;
       switch ($tipo) {

        case 'error':
            $_SESSION['msg'] = '<div class="alert-danger">' . $msg . '</div>';
            break;

        case 'alert':
            $_SESSION['msg'] = '<div class="alert-alert">' . $msg . '</div>';
            break;
        }
    }
}

// Esta função vai exibir sua mensagem onde você quiser
public function get_msg($id)
{
    if (isset($id)) {
        if ($id == $_SESSION['id']) {
            echo $_SESSION['msg']; 
        }
    }
    return FALSE;
}

In your login routine, depending on the result you call the set_msg() function by passing its parameters and on your login page you put the get_msg() function where you want the message to appear.

Example of use of functions:

set_msg('msg_login', 'Login ou senha inválidos', 'error');
get_msg('msg_login');
  • However how will I know if it gave error or not, because in php, I do not know if Voce saw, I do an echo 01 if the login is invalid, and 02 if the user is blocked.

  • Besides I wanted to arrow a text to div.msg

  • In your login routine, instead of you putting "$_SESSION['VALIDATION'] = 01;" you call the set_msg() function and within the div you want you call the get_msg function()

  • something else, when the document runs for the first time it error, because it does not find anything inside message, how to solve ?

  • Fatal error: Call to Undefined Function get_msg() in /opt/lampp/htdocs/Renan/jrassessoria/admin/index.php on line 17 /// //// ta giving this error

  • Puts an if to check if $_SESSION['msg'] is different from empty inside the get_msg function();

  • so : if (!($_SESSION['msg']) == "") { ???

  • if (isset($_SESSION['msg'])) { echo $_SESSION['msg']; }

  • Now you are giving following error, because I have to put a include in the help file in the home page, but it is giving error in the first function. Parse error: syntax error, Unexpected T_PUBLIC in /opt/lampp/htdocs/Renan/jrassessoria/admin/scripts/help.php on line 3

  • what’s on line 3?

  • public Function set_msg($id, $msg, $type)

  • remove the public from both functions!

  • Now the error ta here: Notice: Undefined variable: _SESSION in /opt/lampp/htdocs/Renan/jrassessoria/admin/scripts/help.php on line 25

  • if ($id == $_SESSION['id']) { the line is this

  • gives a session_start(); at the beginning of the two functions.

  • still make the mistake.

  • I updated, as it is all pages for you to view better, to be able to help me.

Show 12 more comments

2

A simpler way: perform the checks directly in php and pass the result to js.

<?php
    if ($_SESSION['VALIDACAO'] == 01) {
        $texto = "Login inválido";
    } else {
        $texto = "Úsuario bloqueado, contacte o administrador do sistema.";
    }
?>

<script>
    $('document').ready(function() {         
        document.getElementById("msg").innerHTML = "<?php echo $texto ?>";
    });
</script>
  • Parse error: syntax error, Unexpected T_IF in /opt/lampp/htdocs/Renan/jrassessoria/admin/index.php on line 4

  • The following is happening, he is reading the document, and is giving error because there is nothing inside the variable.

  • What is the line 4 in your file index.php?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.