Writing your first python CGI ajax script

This post will demonstrate how to write a Python-CGI script using Ajax. Install python and set the environment path. Create a directory for your project and create run.bat with “python-m CGIHTTPServer”. In cgi-bin directory create a file time.py

The best part is that you don’t need Apache server to run this demo so you dont have to install Apache server. First you need to write HTML page and JavaScript.

<html>
<body>
    <script type="text/javascript">
        function ajaxFunction()
        {
            var xmlHttp;
 
            try
            {
                //Firefox,Opera 8.0+ safari
                xmlHttp = new XMLHttpRequest();
            }
 
            catch (e)
            {
                //Inter Expplorer
                try
                {
                    xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
                }
 
                catch(e)
                {
                    try 
                    {
                        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    catch (e) 
                    {
                        alert("Your browser does not support AJAX!");
                        return false;
                    }
                }
            }
 
 
            xmlHttp.onreadystatechange = function()
            {
                if(xmlHttp.readyState == 4)
                {
                    document.myForm.time.value = xmlHttp.responseText;
                }
            }
 
            xmlHttp.open("Get","http://localhost:8000/cgi-bin/time.py",true);
            xmlHttp.send(null);
        }            
  </script>
 
  <form name="myForm">
      Name: <input type="text"  name="username" />
        Time: <input type="text" name="time" />                      
    </form>
</body>
</html>
#!/usr/bin/env python
# simple.cgi  
import cgitb 
cgitb.enable() 
import time
print "Content-type: text/html"  #this part is important to tell the browser that output is html text.
print  
print time.strftime('%Y-%m-%d %X', time.localtime() )

command to run server: python -m CGIHTTPServer

Scroll to Top