Simple Ajax Request

Simple Ajax request example. This example is requesting the output of a cgi python script and inserts the result into an existing div:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My First Ajax Test</title>

	<script type="text/javascript">
		function showAjaxResults() {

			alert("Starting Ajax Result");
			myReq = new XMLHttpRequest();"GET", "", false);

			//set a custom HTTP Header
					"this is the value of my custom header");

			//log to javascript console all headers - there you can find http status codes etc.

			// now fill the results-div with the received text
			document.getElementById("results").innerHTML = myReq.responseText;

			// you could also replace the existing body with the received text
			//document.body.innerHTML = myReq.responseText;

	<button onclick="showAjaxResults()">Show me the Ajax Results</button>

	<div id="results">here you will find the results....</div>


To related python script is an really simple script, but nevertheless you can find the source below:


import cgi
import cgitb
from symbol import or_test

print "Content-type:text/html"
print 'Access-Control-Allow-Methods: POST, GET, OPTIONS'
print "Access-Control-Allow-Origin: *rn"
print ''
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print '</body>'
print '</html>'

In another Post I will explain why there are the Header with Access-Control-Allow *. They are required in case of cross site scripting.

Note: This example isn’t fully correct, because the returned text from the python class is a complete html text, but this is filled in an already existing html website.

The reason for that is, that I used ths python script for several different tests. To have a valid result after calling the ajax request in the first source, you should remove the <html> <head> <body> fragments from the python script.