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" "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.

 

HTTP Request using JSP

In the last days I worked a lot around HTTP Request and Response stuff and here I would like to share some of the stuff.
The following code snippet shows a JSP page that sends an HTTP Request to a specified URL. It is also possible to specify custom headers (see myVeryCoolHeader) and it is also possible to send basix authentication for username/password secured websites:

<%@ page import="java.net.HttpURLConnection"%>
<%@ page import="java.net.URL"%>
<%@ page import="java.io.*" %>
<%
	
	URL myURL= new URL("http://mydummysite.org/testing/website.html");
	HttpURLConnection myconn = (HttpURLConnection) myURL.openConnection();

	String mybody = "This is the HTTP-Body. You can put here any text stuff you want";

	myconn.setRequestMethod("GET");
	myconn.setDoOutput(true);
	myconn.setUseCaches(false);
	myconn.setRequestProperty("myVeryCoolHeader", "My very cool header -value");
	
	
	// if the website requires basic authentication:
	boolean isSecuredWebsite = true;
	if (isSecuredWebsite){
		String login = "myUSER" + ":" + "myPassword";
		String loginEncoded = new sun.misc.BASE64Encoder().encode(login.getBytes());
		myconn.setRequestProperty("Authorization", "Basic " + loginEncoded);
	}
	
	// request the content as html text
	myconn.setRequestProperty("Content-Type", "text/html");
	myconn.setRequestProperty("Content-Length", String.valueOf(mybody.length()));
	
	// write the stuff to the output stream 
	OutputStreamWriter writer = new OutputStreamWriter(myconn.getOutputStream());
	writer.write("nn" + mybody);
	writer.flush();
	
	
	
	if(myconn.getResponseCode()== 200){
		// everyting ok, put the output from SAP into the HTTP Response
		BufferedReader reader = new BufferedReader(new InputStreamReader(myconn.getInputStream()));

		
		// write the stuff to the website
		String line = reader.readLine();
		while (line != null){
			out.println(line);
			line = reader.readLine();
		}
		reader.close();
		
	} else if(myconn.getResponseCode() == 401) {  
		// Catch the "not Authorized" Status code
		out.println("This Website is secured by Username and Password. <br>");
		
		out.println("<b>DEBUG-INFO</b>: <br>" +myconn.getHeaderField("WWW-Authenticate"));
		out.println("<br>URL: " + myURL.toString());
		out.println("<br>HTTP-Response Code: " + myconn.getResponseCode() + " " + myconn.getResponseMessage());


		
	} else{
		// all other errors like redirect, etc.
		out.println("An unexpected error appeared. Please inform your administrator about this issue. <br>");
		out.println("<b>DEBUG-INFO</b>: <br>");
		out.println("<br>URL: " + myURL.toString());
		out.println("<br>HTTP-Response Code: " + myconn.getResponseCode() + " " + myconn.getResponseMessage());
		
	}


	writer.close();
	myconn.disconnect();
	
%>