Ajax python “hello server” example

Ajax python “hello server” example

Ajax provides direct messaging between a browser page and the server from where the browser page originated. For example, only a part of a web page may be loaded using Ajax (like google maps).

There are examples of Ajax on the web, but i have not found one of them that used mod_python as a back-end. I thought I would provide a simple “Hello world” example as reference:

I assume you have apache2 and mod_python working. I have Python Version 2.5.2 and Apache2 version 2.2.8 on Ubuntu.

File “test_ajax_helloserver.html” : contains the ajax javascript code that your browser will execute.
File “hello_server.py” : contains the ajax response that mod_python will execute on the server

Copy and paste the text below into your favourite text editor.
Save the two files in the same directory/folder under your Apache mount point.
Load “test_ajax_helloserver.html” through your Apache webserver, and test it by clicking the button.

test_ajax_helloserver.html

 
<html><head><title>AJAX Hello Server mod_python (hello_server.py) Test</title>
<script type="text/javascript">
var req;
function sendServerRequest(){
   req = newXMLHttpRequest(); // register the callback function
   req.onreadystatechange = updateMsgOnBrowser
   //specify url correctly in open(requestMethod,url,isAsync,username,password)
   req.open("POST", "hello_server.py", true); //or "POST"
   req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   //get the text input element (payload) and send it to server
   var msg_value = (document.getElementById("testmsg")).value;
   req.send("form_send="+msg_value);  //send(payload) send(null)=no parameters
}
// This is the callback function that called from the server with the XML data
function updateMsgOnBrowser() {
  if (req.readyState == 4) {
     if (req.status == 200) {
        if(req.responseXML == null){
           var msg_display = document.getElementById("display_result");
           msg_display.innerHTML="XML response error<p><b>Content-type:</b>"+
               req.getResponseHeader("Content-type")+"<p><b>Response:</b> "+req.responseText;
        } else {
           testXML=req.responseXML;
	   if (!testXML.documentElement && req.responseStream) { // Microsoft hack
	      testXML.load(req.responseStream); // another reason to drop IE
  	   }
           var stime=(testXML.getElementsByTagName("server")[0]).getAttribute("time");
           var ctype=(testXML.getElementsByTagName("ctype")[0]).firstChild.nodeValue;
           var msgval=" - )" ;
           if (testXML.getElementsByTagName("message")[0].firstChild!=null){
                 msgval=(testXML.getElementsByTagName("message")[0]).firstChild.nodeValue;
           }
           var version=(testXML.getElementsByTagName("version")[0]).firstChild.nodeValue;
           var msg_display=document.getElementById("display_result");
           msg_display.innerHTML="<p><b>Server received:</b>"+msgval+
             "<p><b>Python Version:</b> "+version+"<p><b>Server Time:</b>"+stime+
             "<p><b>Content-type  server:</b>"+ctype+
             "<p><b>Content-type browser:</b>"+req.getResponseHeader("Content-type");
        }
     } else {
       var msg_display = document.getElementById("display_result");
       msg_display.innerHTML = "ERROR: "+ req.status +" "+ req.statusText;
     }
  }
}
//helper function to get a XMLHTTPRequest
function newXMLHttpRequest() {
   try { return new XMLHttpRequest(); } catch(e) {}
   try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP");    } catch (e) {}
   alert("XMLHttpRequest not supported");
   return null;
}
</script>
</head>
<body><h1>Simple javascript ajax to server test</h1>
<input id="testmsg" type="text" value="Hello Ajax server">
<button onclick="sendServerRequest()">Send ajax request to Server</button>
<div id="display_result" style="{background:honeydew;}">
Response from "hello_server.py" on the server will go here </div>
<div id="error_msg"></div>
</body></html>

hello_server.py

 
import  sys,time
def index(req):
    req.content_type="Content-Type: application/xml"
    submit = req.form.getfirst("form_send", "no form parameter")
    s= "<?xml version=\"1.0\"?>  <server time=\"%s\">\
        <ctype>%s </ctype> <message>%s </message> <version>%s </version>\
       </server>" % (time.ctime(),req.content_type,submit,sys.version)
    return s

You would need a different javascript pattern/design if you plan to a have web-page that simultaneously sends multiple Ajax request.

If you get the error “405 Method Not Allowed”, the python module is not processing the “POST request. This may be due to the security configuration of the Web server. You could try changing your “POST” to a “GET” in the javascript. If you get a XML response error it may be because mod_python is not running properly.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.