I’m trying to create an AJAX live search (such as Google Suggest) with python. I’m new to AJAX, so I started reading some tutorials and other useful documentation. I found an example, http://www.w3schools.com/ajax/ajax_aspphp.asp, which is basically what I’m trying to accomplish but this example is for asp/php only. I managed so far to code the python portion of the program, however I’m getting an undefined error.
Below is my javascript code (test.js, which is basically the same as the one from the example):
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","search.py?q="+str,true);
xmlhttp.send();
}
In firefox 4, it comes up with the error “str is undefined”.
Below is my html portion of my python code:
<html>
<head>
<title>Live Search</title>
<script src="http://localhost:8000/test.js" type="text/javascript"></script>
</head>
<body>
<h1> Cities </h1>
Enter Anything: <input type="text" id="sname" onkeyup="showHint(this.text)">
%(search)s
</body>
</html>
Note: before I had onkeyup=”showHint(this.id) but it doesn’t work for some reason.. it keeps passing “sname” as the query instead of what I type into the input field.
Please help
The
<input>element has no attribute text. That’s whythis.textand laterstrare undefined. Maybe<input type="text" id="sname" onkeyup="showHint(this.value)">would do what you want.