Pass variable php to javascript

6

Could someone tell me how to pass a PHP variable to the Javascript code. I know there are already many posts about this and I already tried to apply only that I should be doing something wrong so I decided to ask for help here.

<?php

   $ligacao = mysqli_connect("localhost", "root", "", "publicidades");
   if (mysqli_connect_errno()) {
       echo "Erro na liga��o MySQL: " . mysqli_connect_error();
   }

   if($_POST["categoria"]){

      $sql_img = "SELECT distinct p.id_publicidade, p.nome, p.descricao, p.categoria, p.visualizacoes, p.estado, l.id_utilizador FROM publicidade p, linhapub l WHERE p.id_publicidade = l.id_publicidade and estado = 1 AND categoria IN (".$_POST["categoria"].") ORDER BY visualizacoes DESC";
      $imagem = mysqli_query($ligacao, $sql_img);
      $objeto = mysqli_fetch_assoc($imagem);
      $attempts = $objeto["descricao"];
      $estado = $objeto["estado"];
      $utilizador = $objeto["id_utilizador"];

      $visu = "SELECT visualizacoes FROM publicidade WHERE id_publicidade ='".$objeto["id_publicidade"]."'";
      $obj = mysqli_query($ligacao, $visu);
      $res = mysqli_fetch_assoc($obj);
      $final = $res["visualizacoes"];

      $num_post = mysqli_num_rows($imagem);
      if( $num_post ) {
         if($estado){
             if($final>0){
                echo "<img src=\"$attempts\" alt=\"Não deu!!\">";
                $alterar = "UPDATE publicidade SET visualizacoes  = visualizacoes-1 WHERE descricao = '$attempts'";
                $alteracao =  mysqli_query($ligacao, $alterar);
             }else{
                echo 'O seu tempo de antena acabou';
             }
         }

I want to pass the variable $utilizador to this Javascript function that is on another page:

<script type="text/javascript">
   var autoLoad = setInterval(
   function ()
   {
       var query="";
       for(var i=0; i<array.length; i++){
       query+= (i==0?"":",") + "'"+array[i]+"'";
       }
      $.ajax({
      type: "POST",
      url: "load_post.php",
      data: {categoria:query},
      success: function(dados){
          alert(dados);
      $('#load_post').html(dados);
          $('#load_post').fadeOut(5000);
        Lista(variavel);
      }
    });
      $('#load_post').fadeIn(5000);
   }, 5000); 
</script>

I then when I have the variable I want to call it in function Lista()

I was trying to send through the URL of $utilizador and then do the GET on the other page but for some reason it does not work.

Thank you.

    
asked by anonymous 17.04.2015 / 15:20

3 answers

5

First we have to understand that PHP is a server-side and Javascript client-side language, given this information we know that Javascript is interpreted by the browser as well such as HTML and CSS, so in the same way that you "write" HTML with PHP you can also "write" Javascript (and in many ways, follow some of them):

Direct in PHP

<?php
    $utilizador = 'algum valor';
    echo '<script>var utilizador = "'. $utilizador .'";</script>';

Direct in HTML / Script

<script>
    var utilizador = <?=$utilizador?>;
</script>

In the above cases, if the value of the variable in PHP is a string , you should put quotation marks around the variable to avoid Javascript errors:

    var utilizador = "<?=$utilizador?>";

You can pass an array as json :

<script>
    var dados = <?=json_encode($objeto)?>
</script>

With jQuery.ajax

This option is for the variants that you want to save, do not be in the same JAVASCRIPT file

  

Page with variables (load_post.php)

<?php
    $var = Array(
        'attempts' =>   $objeto["descricao"],
        'estado' =>     $objeto["estado"],
        'utilizador' => $objeto["id_utilizador"]
    );

    header('Content-Type: application/json');
    echo json_encode($var);
    exit;
  

Page with Javascript

$.ajax({
    type: "POST",
    url: "load_post.php",
    data: {categoria:query},
    success: function(dados){
        alert(dados);
        $('#load_post').html(dados);
        $('#load_post').fadeOut(5000);
        Lista(dados.utilizador);
    }
});
    
17.04.2015 / 15:43
0

Make $.ajax() a POST for your PHP, get PHP with $objeto and return it in ajax with <php>echo json_encode($objeto); .

    
17.04.2015 / 15:26
0

It was not clear if the javascript is on the same page, after PHP. If it is simple:

<script type="text/javascript">
   var autoLoad = setInterval(
   function ()
   {
       var utilizador = "<?php echo $utilizador ?>";

Now if you are on another page there, the best thing is with jquery.ajax ()

    
17.04.2015 / 15:44