JavaScript AJAX ASP
JavaScript Basics

JavaScript AJAX ASP

AJAX ASP Example

AJAX is used to create more interactive applications.

AJAX ASP Example

The following example demonstrates how a web page can communicate with a web server while a user types characters in an input field:


Start typing a name in the input field below:


First name:

Example Explained

In the example above, when a user types a character in the input field, a function called showHint() is executed.

The function is triggered by the onkeyup event.

Here is the code:

HTML Code:

<p>Start typing a name in the input field below:</p>
<p>Suggestions: <span id="txtHint"></span></p>

First name: <input type="text" onkeyup="showHint(this.value)">

function showHint(str) {
  if (str.length == 0) {
    document.getElementById("txtHint").innerHTML = "";
  } else {
    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = function() {
      document.getElementById("txtHint").innerHTML = this.responseText;
    }"GET", "gethint.php?q=" + str);

Code Explanation:

  1. First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint placeholder and exit the function.
  2. If the input field is not empty:some text
    • Create an XMLHttpRequest object.
    • Define the function to be executed when the server response is ready.
    • Send the request to an ASP file (gethint.asp) on the server.
    • Note that the q parameter is added to gethint.asp?q=" + str. The str variable holds the content of the input field.

ASP File - "gethint.asp":

The ASP file checks an array of names and returns the corresponding name(s) to the browser:

ASP Code:

// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";

// Get the q parameter from URL
$q = $_REQUEST["q"];

$hint = "";

// Lookup all hints from array if $q is different from ""
if ($q !== "") {
  $q = strtolower($q);
  $len = strlen($q);
  foreach ($a as $name) {
    if (stristr($q, substr($name, 0, $len))) {
      if ($hint === "") {
        $hint = $name;
      } else {
        $hint .= ", $name";

// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;

This code provides real-time suggestions based on the input provided by the user, making the application more interactive.

Take a look into your desired course