Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
<?php
  $query3 = "SELECT message FROM messageslive LIMIT 1";
  $result3 = mysql_query($query3,$connection) or die (mysql_error());
  confirm_query($result3);
  while($userinfo3 = mysql_fetch_array($result3)){
      $msgLive = $userinfo3['message'];
  }
?>

<script type="text/javascript">
  var msg = "<?php echo $msgLive ; ?>";
</script>

What I worry is when the database table has too many data to search and retrieve, so PHP variable $msgLive doesn't have value yet, so Javascript variable var msg get empty value. How to ask javascript wait until PHP variable $msgLive got the value then only transfer the value from php variable to Javascript?

share|improve this question

1 Answer 1

up vote 6 down vote accepted

You shouldn't worry about this because first the server script executes, takes its time to communicate with the database, assigns the msgLive variable a value, and finally it generates the HTML which is sent to the client. During all this time the client waits (and probably curses his ISP for the slow connection he is experiencing :-)). So once the HTML reaches the client browser the javascript variable will have its value set. So no need to tell javascript to wait, javascript doesn't even exist until the server finishes its job and pushes the HTML to client.

share|improve this answer
    
what if I put another php codes <?php $msgLive="12345" ?> at below the javascript codes? The the value of javascript variable var msg will become "12345"? –  zac1987 Jun 12 '11 at 13:25
3  
@zac1987, no matter where you put it. You should really distinguish between server side code and client side code. Those are two completely different processes happening at two different points of time. First the server which generates HTML which is sent to the client and then the client will get hold of it and if this HTML contains javascript it will run inside the browser, ... –  Darin Dimitrov Jun 12 '11 at 13:27
    
So var msg will become "12345". I understood it already. Thank you. –  zac1987 Jun 12 '11 at 13:32
    
but when I declare <?php $username="abc"; ?> then I javascript alert ("<?php echo $username; ?>"); it success alert "abc". But when I switch the code of javascript to above php code, it fail to alert "abc". If as you said php run finish 1st, then only run javascript. Why javascript fail to alert the value of php variable? –  zac1987 Jun 17 '11 at 17:48
1  
@zac1987 Javascript will NEVER execute before php, it makes no sense! –  Connor Smith Jun 17 '11 at 21:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.