7. February 2012
von Blackbam
Nothing new, nothing special... just the working code of a basic Ajax skeleton, as this has to be copied and pasted that often. This example shows an application similar to Google suggest, which searches related values, whenever a key is pressed.

Note: Since jQuery is that popular today, it is possibly better to use this (see jQuery Ajax Tutorial).
index.html - function call and result representation
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax test</title>
<script type="text/javascript" src="ajax.js"></script>

<input type="text" onkeyup="AjaxRequest(this.value);" /><br/>
<p id="result"></p>

ajax.js - request, response and data processing
var XMLHTTP = null;

function AjaxRequest(compString) {

// XMLHTTP-Request Objekt erzeugen, dabei auf Browserkonformität achten
 if(window.XMLHttpRequest) {
  XMLHTTP = new XMLHttpRequest();
 } else if(window.ActiveXObject) {
  try {
   XMLHTTP = new ActiveXObject("Msxml2.XMLHTTP");
  } catch(ex) {
   try {
    XMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
   } catch(ex) {
 XMLHTTP.onreadystatechange = MyRequestExecute;

// wird jedes mal aufgerufen, wenn der XMLHTTP-Request eine neue Stufe erreicht, bei 4 ist die Antwort des Servers eingetroffen
function MyRequestExecute() {
 // responseText als Javascript-String, responseXML als Javascript XML-DOM-Element, status Statuscode, statusText des. Beschreibung
 if(XMLHTTP.readyState == 4) {
  document.getElementById("result").innerHTML = XMLHTTP.responseText;

The server side


// Datenbankverbindung
try {
 $db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASSWORD);
 $sql = "SELECT * FROM tags WHERE username = '".$_GET['compString']."'";
 $horst = $db->query($sql);
} catch (Exception $e) {
    echo 'Verbindungsaufbau fehlgeschlagen: ',  $e->getMessage(), "\n";

echo $_GET['compString']."< pre >".$horst."</  pre >";
// Definition der Konstanten

Dieser Eintrag wurde am 7. February 2012 um 10:10 in der Kategorie JavaScript / Ajax veröffentlicht. You can book the comments for this article RSS 2.0. Feedback, discussion, commendation and critics are welcome: Write a comment or trackback.

Tags: , , ,

No comments yet

Kommentare abonnieren (RSS) or URL Trackback

Leave a comment: