My TA says that GET request by following AJAX code is being sent twice. But I don't see how nor I am able to fix it. What is general approach how to deal with that?
It is simple page with search box giving advices as you type. Problem has to be somewhere in getByPrefix function.
JS code:
function set(arg)
{
var searchtext = document.getElementById("searchtext");
searchtext.value = arg.innerHTML;
showMatches(searchtext);
}
function getByPrefix(prefix, callback)
{
var prefixes = [];
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var response = JSON.parse(xmlhttp.responseText);
for (var i = 0; i < response.length; i++) // prepsani do jednoducheho indexovaneho pole
{
prefixes.push(response[i].drug);
}
callback(prefixes);
}
}
xmlhttp.open("GET","prefixes.php?q="+prefix,true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
xmlhttp.setRequestHeader('Cache-Control', 'no-cache');
xmlhttp.send();
}
function action2(text)
{
getByPrefix(text.value, showMatches);
}
function showMatches(text)
{
var matches = text;
var form = document.getElementById("search");
var results = document.getElementById("results");
if (results != null)
form.removeChild(results);
var div = document.createElement("div");
div.id = "results";
for (var i =0; i < matches.length; i++)
{
var p = document.createElement("p");
p.className = "hidden";
p.onclick = (function(a) { return function(){ set(a); }})(p);
p.innerHTML = matches[i];
div.appendChild(p);
}
if (matches.length>1 && text.value != "")
form.appendChild(div);
if (matches.length==1 && text.value != matches[0])
form.appendChild(div);
}
PHP code:
<?php
function head()
{
global $db;
?>
<head>
<title>Search</title>
<?php head_common(); ?>
<script type="text/javascript" src="js/main.js"></script>
</head>
<?php
}
function body()
{
?>
<body>
<?php heading(); ?>
<div>
<img src="img/logo.jpg" height="200" width="400">
<form id="search" method="get" action="index.php">
<p>
<input name="page" value="results" type="hidden">
<input name="part" value="1" type="hidden">
<input name="hledej" id="searchtext" autocomplete="off" onKeyUp="action2(this)" type="text">
<button>Hledej</button>
</p>
</form>
</div>
<?php footer(); ?>
</body>
<?php
}
?>