Pass php variable to javascript

Asked

Viewed 22,485 times

8

Someone could tell me how to pass a PHP variable to Javascript code. I know there are already many posts about it and I’ve tried to apply only that I must be doing something wrong so I decided to ask here for help.

<?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 here $utilizador for 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 upload the URL to $utilizador and then do the GET on the other page but for some reason it doesn’t work.

Thank you.

3 answers

8


First we have to understand that PHP is a language server-side and Javascript client-side, given this information we then know that Javascript is interpreted by the browser, as well 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>

Beware in previous cases that if the value of the variable in PHP is a string, quote around the variable to avoid errors in Javascript:

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

Can pass a array as json:

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

With jQuery.ajax

THIS OPTION IS FOR IF THE VARIABLES YOU WANT TO RESCUE ARE NOT 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 the 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);
    }
});
  • Thank you very much, really. I’ve been delirious since 12 o'clock and I wasn’t getting anywhere. Thank you very much!

1

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

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

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

  • 2

    Hello @Ivannack, welcome to [en.so]! I would like to ask you to develop a little bit more about using the jquery.ajax() in the context of this question, since this may be the solution to the problem for both @OP and others who access the question!

0

Does with the $.ajax() a POST for your PHP, take your PHP $objeto and return it on ajax with <php>echo json_encode($objeto);.

Browser other questions tagged

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