title: PHP session variable and javascript variable are asynchronous
body: <p>I have a captcha generator php script:</p>
  
  <pre><code>&lt;?php
      session_start();
      header ("Content-type: image/png");
  
      /*irrelevant parts here*/
  
      $word = "";    
      for ($i = 0; $i &lt; 4; $i++) {
          $letter = $letters[rand(0, $len - 1)];         
          imagettftext($image, 15, 0, $i*50+25, 50, $text_color, $font, $letter);
          $word .= $letter;
      }
      $_SESSION['captcha_string'] = $word;        
      imagepng($image);
  ?&gt;
  </code></pre>
  
  <p>I call it this way in my HTML/PHP page:</p>
  
  <pre><code>&lt;?php session_start(); ?&gt;
  
  &lt;!DOCTYPE html&gt;
  
  .. some irrelevant code here ..
  
  &lt;img id="captchaimg" src="captcha_generator.php"&gt; 
  </code></pre>
  
  <p>And this is my javascript code which is <strong>on the same HTML/PHP page</strong> (I call this function with a button click):</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
   function validCaptcha() {           
   var a = &lt;?php echo json_encode($_SESSION['captcha_string']); ?&gt;;
   alert(a);
   }
  &lt;/script&gt;
  </code></pre>
  
  <p>My problem is that the javascript "is late", it gets the previous value of the session variable, not the actual. I think the reason is that when the page is loading the php runs AFTER the javascript did get the session variable. So, the javascript sees the previous session variable, while there is already a new one.
  How can I get the ACTUAL session variable in the javascript function?</p>
  
  <p><strong>UPDATE</strong> to the question: when does the javascript function get the session variable? <strong>When the page is loading or when the user clicks the button?</strong></p>