Skip to content

AJAX ASP

Server Interaction: Live Search (Conceptual Example)

Section titled “Server Interaction: Live Search (Conceptual Example)”

Asynchronous JavaScript is powerful for creating interactive user experiences, such as providing live search suggestions as a user types.

This example demonstrates the client-side JavaScript using Fetch API and a conceptual server-side part (represented here by simple Node.js/Express and PHP snippets). The outdated ASP Classic example has been removed.

This demonstrates how a web page can communicate with a server endpoint to get suggestions while a user types characters in an input field.

<p>**Start typing a name in the input field below:**</p>
<form onsubmit="return false;"> <!-- Prevent default submission -->
<label for="txtName">First name:</label>
<input type="text" id="txtName" name="name" autocomplete="off">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
<p><small>Server endpoint: /api/suggestions</small></p>
const nameInput = document.getElementById('txtName');
const hintSpan = document.getElementById('txtHint');
let debounceTimer; // For debouncing requests
async function showHint(query) {
// Basic validation
if (query.length === 0) {
hintSpan.innerHTML = '';
return;
}
hintSpan.innerHTML = '<i>Searching...</i>'; // Provide feedback
try {
// Construct the URL with the query parameter
const url = `/api/suggestions?q=${encodeURIComponent(query)}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Server error: ${response.status}`);
}
const suggestions = await response.json(); // Expecting JSON array of strings
if (suggestions.length > 0) {
// Sanitize suggestions before displaying (basic example)
const safeSuggestions = suggestions.map(s =>
String(s).replace(/</g, "&lt;").replace(/>/g, "&gt;")
);
hintSpan.innerHTML = safeSuggestions.join(', ');
} else {
hintSpan.innerHTML = 'no suggestion';
}
} catch (error) {
console.error('Error fetching suggestions:', error);
hintSpan.innerHTML = '<i style="color:red;">Error fetching suggestions</i>';
}
}
nameInput.addEventListener('input', (event) => {
const query = event.target.value;
// Debounce: Clear the previous timer and set a new one
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
showHint(query);
}, 300); // Wait 300ms after user stops typing
});
  • Event Listener: An input event listener is attached to the text field. It fires whenever the value changes.
  • Debouncing: A setTimeout (debouncing) mechanism is used to prevent sending a request on every single keystroke. It waits until the user pauses typing for a brief period (e.g., 300ms).
  • showHint Function: This async function handles the logic.
  • Input Check: It checks if the input field is empty; if so, it clears hints and returns.
  • Feedback: It provides ‘Searching…’ feedback to the user.
  • Fetch Request: It uses fetch to make a GET request to a server endpoint (e.g., /api/suggestions) with the user’s input (query) as a URL parameter (?q=...). encodeURIComponent ensures the query is safely included in the URL.
  • Error Handling: It includes try...catch and checks response.ok for robust error management.
  • JSON Parsing: It expects the server to return a JSON response (an array of suggestion strings) and parses it using response.json().
  • Display Results: It updates the txtHint span with the suggestions (joined by commas) or ‘no suggestion’. Basic sanitization (replace(/</g, "&lt;")) is included as a minimal security measure against HTML injection, though server-side validation/sanitization is crucial.
  1. Receive the request and extract the query parameter (e.g., ‘q’).
  2. Perform a lookup (e.g., query a database, search an in-memory list) based on the query.
  3. Format the results as a JSON array.
  4. Send the JSON response back to the client.
// --- Server-Side (Node.js with Express) ---
const express = require('express');
const app = express();
const port = 3000;
// Sample data (in a real app, this would likely come from a database)
const names = [
"Anna", "Amanda", "Alice", "Bob", "Brittany", "Barbara",
"Charles", "Cindy", "Cinderella", "David", "Diana", "Doris", // ... more names
];
app.get('/api/suggestions', (req, res) => {
const query = (req.query.q || '').toLowerCase(); // Get 'q' query param, default to empty string
let suggestions = [];
if (query.length > 0) {
suggestions = names.filter(name =>
name.toLowerCase().startsWith(query)
);
}
// Set content type to JSON and send the array
res.setHeader('Content-Type', 'application/json');
res.json(suggestions);
});
app.listen(port, () => {
console.log(`Suggestion API listening at http://localhost:${port}`);
});
<?php
// --- Server-Side (PHP - e.g., get_suggestions.php) ---
// Sample data (replace with database query in real application)
$names = [
"Anna", "Amanda", "Alice", "Bob", "Brittany", "Barbara",
"Charles", "Cindy", "Cinderella", "David", "Diana", "Doris", // ... more names
];
$query = isset($_GET['q']) ? strtolower($_GET['q']) : '';
$suggestions = [];
if (!empty($query)) {
foreach ($names as $name) {
// Simple case-insensitive starts-with check
if (strpos(strtolower($name), $query) === 0) {
$suggestions[] = $name;
}
}
}
// Set header to indicate JSON response
header('Content-Type: application/json');
// Encode the array as JSON and output it
echo json_encode($suggestions);
?>

Important: These server-side examples are simplified. Real-world applications require proper input validation, sanitization, error handling, potentially more efficient database querying, and security considerations.