dedtech.info

Information about computer technology.

Integrate Python With Ajax

This blog post will explain how to integrate Python with AJAX. The code that is displayed below will create a form and define the AJAX callback function. There will be a lone textbox to enter input into. What the form will do is check the textbox for input and call a server side Python file.

<!DOCTYPE html>
<html>
<body>

<input type="text" onkeyup="showHint(this.value)">
<span id="query"></span>

<script>
function showHint(str) {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
    document.getElementById("query").innerHTML =
    this.responseText;
  }
  xhttp.open("GET", "print.py?q="+str);
  xhttp.send();   
}
</script>

</body>
</html>

For the Python code, a header will have to be placed on top.

#!C:\python\python.exe
print("Content-Type: text/html\n")

The required library has to be imported.

import cgi

The variable query will initialize the CGI class.

query = cgi.FieldStorage()

The variable result will hold the value retrieved from the q variable that was passed with a URL.

result = query["q"].value

A print statement will display how many characters that were entered into the textbox.

print(len(result))

This is what the whole Python code looks like.

#!C:\python\python.exe
print("Content-Type: text/html\n")
import cgi
query = cgi.FieldStorage()
result = query["q"].value
print(len(result))

Leave a Reply

Your email address will not be published. Required fields are marked *