title: How Do I Send a Response to a POST Request with Python?
body: <p>I am trying to implement a simple webpage that uses AJAX to update some text when I press a button. I am using HTML for the page, Javascript for the client side, and Python for the server side. I am using pure CGI for educational purposes.</p>
  
  <p>I am able to get the POST request all the way through my Python script correctly, but I can't find what I should do after that in order to return a value to tthe ResponseText field.</p>
  
  <p><strong>The Code</strong></p>
  
  <p>index.html:</p>
  
  <pre><code>&lt;html&gt;
    &lt;head&gt;
      &lt;title&gt;
        test
      &lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;button onclick="buttonClicked()"&gt;
        click me
      &lt;/button&gt;
      &lt;script&gt;
  
        function buttonClicked() {
            document.getElementById("modify").innerHTML = post('clicked=true', 'input.py')
        }
  
        function post(data, dest) {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {
                    return xmlhttp.responseText;
                }
            }
            xmlhttp.open("POST", dest, true);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
            xmlhttp.send(data);
        }   
  
      &lt;/script&gt;
      &lt;p id="modify"&gt;
        this is the text to be modified by the button
      &lt;/p&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>input.py:</p>
  
  <pre><code>#!/usr/bin/python
  
  import cgi
  input = cgi.FieldStorage()
  
  with open('/var/www/test/output.txt', 'w') as f:
      f.write(input.getvalue("clicked") + "\n")
  
  clicked = input.getvalue("clicked") == "true"
  
  with open('/var/www/test/output.txt', 'a') as f:
      f.write("clicked: " + str(clicked))
  </code></pre>
  
  <p>output.txt:</p>
  
  <pre><code>true
  clicked: True
  </code></pre>
  
  <p>The initial webpage looks as expected. After clicking the button, the text is modified to say <code>undefined</code>, which makes sense because I haven't sent anything back.</p>
  
  <p><strong>How do I send a response to POST with Python?</strong></p>
  
  <p>Edit:</p>
  
  <p>I tried <code>print</code>, <code>print()</code>, and <code>sys.stdout.write()</code>; none did the trick.</p>