如何使用javascript从外部文件加载php变量

I had this code inside the <div id="chtmsg"> on a page that shows a messenger...

PHP :

if($perguntas){
  for($c=0;$c<count($perguntas);$c++){
    $perguntas[$c]->tipo == 'F' ? $class = 'message_F' : $class = 'message_P';
    $hora = substr($perguntas[$c]->hora, 0, 5);
    echo "<li class=\"".$class."\"><p>".$perguntas[$c]->mensagem."</p><span>".$pergunta->databr($perguntas[$c]->data)." - ".$hora."</span></li>";
    if($perguntas[$c]->tipo=='F' and $perguntas[$c]->status == 0){
      $pergunta->marcaRespLida($perguntas[$c]->id);
    }
  }
}

It works very well. So, I wanted to load it with js to refresh all new messages only inside the div #chtmsg and then I created a file msg.php and with the <?php include("msg");?> it continues working good, but with js I needed to put the path...

HTML :

$(document).ready(function () {
    setInterval(function() {
        $.get(hostGlobal+'site/modulos/produto/msg.php', function (result) {
            $('#chtmsg').html(result);
            scTop();
        });
    }, 3000);
});

But its shows the error inside de div...

Notice: Undefined variable: perguntas in /Applications/XAMPP/xamppfiles/htdocs/sisconbr-sistema-novo/site/modulos/produto/msg.php on line 3

I tested other codes inside the msg.php file and works ok without variables...

Just a thought...

Your first line in PHP

if($perguntas){

Should perhaps check if defined like so

if(isset($perguntas)){

My suggestion explained in another answer here

For better code, You should preferably use:

if (isset($perguntas) && is_array($perguntas)){