In the AJAX example below we will demonstrate how a web page can communicate with a web server online as a user enters data into a standard HTML form.

Example Explained - The HTML Form

<form> 
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>

Example Explained - The showHint() Function

The showHint() function is a very simple JavaScript function placed in the <head> section of the HTML page.

The function contains the following code:

function showHint(str)
{
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
  }
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  } 
var url="";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

Example Explained - The GetXmlHttpObject() Function

The example above calls a function called GetXmlHttpObject().

The purpose of the function is to solve the problem of creating different XMLHTTP objects for different browsers.

The function is listed below:

function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}

Example Explained - The stateChanged() Function

The stateChanged() function contains the following code:

function stateChanged() 
{ 
if (xmlHttp.readyState==4)
{ 
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}

The stateChanged() function executes every time the state of the XMLHTTP object changes.

When the state changes to 4 ("complete"), the content of the txtHint placeholder is filled with the response text.

Enjoy Code.

Dani AI

Generated

This thread shows a classic XHR-based autocomplete demo from . It’s fine as a learning example, but there are a few practical gaps worth closing: debounce rapid typing, cancel in-flight requests, build query strings safely when sending more than one variable (answering ), provide accessible keyboard navigation (what asked about), and avoid inserting unsanitized HTML from the server.

A compact, modern approach uses Fetch + AbortController, URLSearchParams for multiple params, and a debounce wrapper. The server should return JSON (an array of suggestions) to avoid XSS and make rendering predictable. Example pattern (server returns JSON array):

const input = document.querySelector('#txt1');
let controller;
const debounce = (fn, ms=250) => { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; };

async function fetchHints(q, extra) {
  if (!q) return render([]);
  if (controller) controller.abort();
  controller = new AbortController();
  const params = new URLSearchParams({ q, extra }).toString();
  const res = await fetch('/ajaxhint.php?' + params, { signal: controller.signal, cache: 'no-store' });
  if (!res.ok) return render([]);
  const items = await res.json();
  render(items);
}

input.addEventListener('input', debounce(e => fetchHints(e.target.value, 'someDate')));

For dropdown + keyboard (replying to ): render suggestions inside an element with role="listbox" and children role="option", manage aria-activedescendant, and handle ArrowUp/ArrowDown/Enter to move/select. Keep the rendering code separate from server logic and avoid global XHR variables.

Note on ’s concat example: build params with URLSearchParams or include the = (e.g., &name=) and use encodeURIComponent so values with special characters are safe. Server-side should trim, limit results, and throttle to protect resources.

Recommended Answers

All 3 Replies

Good job, not going to test it but it gave me an idea and I might even scrape some code from it to mine. I already have the ajax portion I'm just going to add the idea of a ajaxhint.php and onkeyup.

Any idea of how to get it to "drop down" below the html input and let you down arrow and enter, or click to pass it to the html input? Wait.. As i'm typing this, i'm getting the idea of how to do it. I'll post it if I succeed.

Thanx again for the code!

anyone know how you would pass two variables instead of jus the one e.g. to allow the user to search by 'date' and 'name'
thx

url=url+"?q="+str;
url=url+"&anothervariable"+var1;
url=url+"&andanothervariable"+var2;
url=url+"&sid="+Math.random();

A bit like that. ? means you're going to start adding variable, then you use & to seperate them.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.