Jul 232013
 

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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My First Ajax Test</title>
</head>
<body>

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

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

			myReq.open("GET", "https://philipp-boss.de/cgi-bin/test.py", false);

			//set a custom HTTP Header
			myReq.setRequestHeader("myVeryCoolHeader",
					"this is the value of my custom header");
			myReq.send();

			//log to javascript console all headers - there you can find http status codes etc.
			console.log(myReq.getAllResponseHeaders());

			// 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;
		}
	</script>

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

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

</body>
</html>

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

#!/usr/bin/python

import cgi
import cgitb
from symbol import or_test
cgitb.enable()

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.

 

Sorry, the comment form is closed at this time.