title: Javascript and PHP in one file (form handling and XMLHTTPRequest)
body: <p>I am confused about my homework requirements: we need to put JS, HTML and PHP code in the same file xxx.php.</p>
  
  <p>There is a form in the HTML, and once I submit the form, I need to send a request (XMLHTTPRequest) to myPHP.php with the form inputs (using POST to transfer the form data PHP). The PHP file will retrieve the form inputs, reformat it to the syntax of the API and send it to the Google API to get JSON object.</p>
  
  <p>I am a beginner of PHP and JS, and I don't know how to combine them in the same file and do the homework based on the requirements. Like, how to send the JSON object obtained in PHP to Javascript.</p>
  
  <p>Here is framework of my code (myPHP.php):</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt;
  &lt;head&gt;
  
      &lt;script type="text/javascript"&gt;
  
          // show the result
          function show() {
              var xmlhttpreq = new XMLHttpRequest();
             
              var keyword = document.getElementById("keyword").value;
              var post_data = "keyword=" + keyword;
  
              xmlhttpreq.onreadystatechange = function() {
                  if (this.readyState == 4 &amp;&amp; this.status == 200) {
                      var jsonObj = JSON.parse(this.responseText);
                      createTable(jsonObj);
                  }
              };
  
              xmlhttpreq.open("POST", "myPHP.php", true);
              xmlhttpreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
              xmlhttpreq.send(post_data);
          }
  
          function createTable(object) {
              var out = "xxx";
              document.getElementById("display").innerHTML = out;
          }
      &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;div id="display"&gt;&lt;/div&gt;
  
  &lt;form action="myPHP.php" name="myForm" method="POST"&gt;
      &lt;b&gt;Keyword &lt;/b&gt;&lt;input type="text" id="keyword" name="keyword"&gt;
      &lt;br&gt;
      
      &lt;button type="submit" onclick="show()" name="search"&gt;Search&lt;/button&gt;
  &lt;/form&gt;
  
  
  &lt;?php
  if (isset($_POST["search"])) {
      // extract the form data
      $keyword = $_POST["keyword"];
  
      // geocode the address
      $location = urlencode($location);
      // google map geocode api url
      $url = "xxxxxxxx";
      $res_json = file_get_contents($url);
      echo $res_json;
  }
  ?&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>