w3schools    w3Schools
Search W3Schools :
   
HOME HTML CSS XML JAVASCRIPT ASP PHP SQL MORE...   References Examples Forum About
ADVERTISEMENTS

XML Certification
Download XML editor
Custom Programming
 
Table of contents
PHP Basic
PHP HOME
PHP Intro
PHP Install
PHP Syntax
PHP Variables
PHP String
PHP Operators
PHP If...Else
PHP Switch
PHP Arrays
PHP Looping
PHP Functions
PHP Forms
PHP $_GET
PHP $_POST

PHP Advanced
PHP Date
PHP Include
PHP File
PHP File Upload
PHP Cookies
PHP Sessions
PHP E-mail
PHP Secure E-mail
PHP Error
PHP Exception
PHP Filter

PHP Database
MySQL Introduction
MySQL Connect
MySQL Create
MySQL Insert
MySQL Select
MySQL Where
MySQL Order By
MySQL Update
MySQL Delete
PHP ODBC

PHP XML
XML Expat Parser
XML DOM
XML SimpleXML

PHP and AJAX
AJAX Introduction
XMLHttpRequest
AJAX Suggest
AJAX XML
AJAX Database
AJAX responseXML
AJAX Live Search
AJAX RSS Reader
AJAX Poll

PHP Reference
PHP Array
PHP Calendar
PHP Date
PHP Directory
PHP Error
PHP Filesystem
PHP Filter
PHP FTP
PHP HTTP
PHP Libxml
PHP Mail
PHP Math
PHP Misc
PHP MySQL
PHP SimpleXML
PHP String
PHP XML
PHP Zip

PHP Quiz
PHP Quiz
PHP Exam

Selected Reading
Web Statistics
Web Glossary
Web Hosting
Web Quality

W3Schools Tutorials
W3Schools Forum

Helping W3Schools

 

PHP and AJAX Live Search

Previous Next

AJAX can be used for a more user friendly and interactive search.


AJAX Live Search

In the AJAX example below we will demonstrate a live search, where the server gets search results while the user types.

Live search has many benefits compared to traditional searching:

  • Matching results are shown as you type
  • Results narrow as you continue typing
  • If results become too narrow, remove characters to see a broader result

Search for a W3Schools page in the Box Below

This example consists of four pages:

  • a simple HTML form
  • a JavaScript
  • a PHP page
  • an XML document

In this example the results are found in an XML document (links.xml). To make this example small and simple, only eight results are available.


The HTML Form

This is the HTML page. It contains a simple HTML form, style for the form and a link to a JavaScript:

<html>
<head>
<script src="livesearch.js"></script> 
<style type="text/css"> 
#livesearch
  { 
  margin:0px;
  width:194px; 
  }
#txt1
  { 
  margin:0px;
  } 
</style>
</head>
<body>
<form>
<input type="text" id="txt1" size="30"
onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>
</body>
</html>

Example Explained - The HTML Form

As you can see, the HTML page above contains a simple HTML form with an input field called "txt1".

The form works like this:

  1. An event is triggered when the user presses, and releases a key in the input field
  2. When the event is triggered, a function called showResult() is executed.
  3. Below the form is a <div> called "livesearch". This is used as a placeholder for the return data of the showResult() function.

The JavaScript

The JavaScript code is stored in "livesearch.js" and linked to the HTML document:

var xmlHttp;
function showResult(str)
{
if (str.length==0)
 { 
 document.getElementById("livesearch").
 innerHTML="";
 document.getElementById("livesearch").
 style.border="0px";
 return;
 }
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request");
 return;
 } 
var url="livesearch.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged ;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
} 

function stateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
 document.getElementById("livesearch").
 innerHTML=xmlHttp.responseText;
 document.getElementById("livesearch").
 style.border="1px solid #A5ACB2";
 } 
}
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 GetXmlHttpObject function is the same as in the PHP AJAX Suggest chapter.

The showResult() Function

This function executes every time a character is entered in the input field.

If there is no input in the text field (str.length == 0) the function sets the return field to empty and removes any border around it.

However, if there is any input in the text field the function executes the following:

  1. Defines the url (filename) to send to the server
  2. Adds a parameter (q) to the url with the content of the input field
  3. Adds a random number to prevent the server from using a cached file
  4. Calls on the GetXmlHttpObject function to create an XMLHTTP object, and tells the object to execute a function called stateChanged when a change is triggered
  5. Opens the XMLHTTP object with the given url.
  6. Sends an HTTP request to the server

The stateChanged() Function

This function executes every time the state of the XMLHTTP object changes.

When the state changes to 4 (or to "complete"), the content of the txtHint placeholder is filled with the response text, and a border is set around the return field. 


The PHP Page

The server page called by the JavaScript code is a PHP file called "livesearch.php".

The code in the "livesearch.php" checks the XML document "links.xml". This document contains titles and URL's of some pages on W3Schools.com.

The code searches the XML file for titles matching the search string and returns the result as HTML:

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("links.xml");
$x=$xmlDoc->getElementsByTagName('link');
//get the q parameter from URL
$q=$_GET["q"];
//lookup all links from the xml file if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<($x->length); $i++)
 {
 $y=$x->item($i)->getElementsByTagName('title');
 $z=$x->item($i)->getElementsByTagName('url');
 if ($y->item(0)->nodeType==1)
  {
  //find a link matching the search text
  if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
   {
   if ($hint=="")
    {
    $hint="<a href='" . 
    $z->item(0)->childNodes->item(0)->nodeValue . 
    "' target='_blank'>" . 
    $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
    }
   else
    {
    $hint=$hint . "<br /><a href='" . 
    $z->item(0)->childNodes->item(0)->nodeValue . 
    "' target='_blank'>" . 
    $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
    }
   }
  }
 }
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
 {
 $response="no suggestion";
 }
else
 {
 $response=$hint;
 }
//output the response
echo $response;
?>

If there is any text sent from the JavaScript (strlen($q) > 0) the following happens:

  1. PHP creates an XML DOM object of the "links.xml" file
  2. All  "title" elements (nodetypes = 1) are looped through to find a name matching the one sent from the JavaScript
  3. The link containing the correct title is found and set as the "$response" variable. If more than one match is found, all matches are added to the variable
  4. If no matches are found the $response variable is set to "no suggestion"
  5. The $result variable is output and sent to the "livesearch" placeholder

Previous Next


Learn XML with <oXygen/> XML Editor - Free Trial!

oXygen - Probably The World's Best XML Editor   

oXygen helps you learn to define, edit, validate and transform XML documents. Supported technologies include XML Schema, DTD, Relax NG, XSLT, XPath, XQuery, CSS.

Understand in no time how XSLT and XQuery work by using the intuitive oXygen debugger!

Do you have any XML related questions? Get free answers from the oXygen XML forum and from the video demonstrations.

Download a FREE 30-day trial today!


 
WEB HOSTING
Name Registration
Domain Name
Registration & More!
$15 Domain Name
Registration
Save $20 / year!
Buy UK Domain Names
Register Domain Names
Cheap Domain Names
Cheap Web Hosting
Best Web Hosting
PHP MySQL Hosting
Top 10 Web Hosting
UK Reseller Hosting
Web Hosting
FREE Web Hosting
WEB BUILDING
Website Templates
Flash Templates
Website Builder
Internet Business Opportunity
Custom Programming
FREE Trial or Demo
Web Content Manager
Forms,Web Alerts,RSS
Download XML editor
FREE Flash Website
FREE Web Templates
EDUCATION
US Web Design Schools
HTML Certification
JavaScript Certification
XML Certification
PHP Certification
ASP Certification
Home HOME or Top of Page Validate   Validate   W3C-WAI level A conformance icon Printer Friendly  Printer Friendly

W3Schools is for training only. We do not warrant the correctness of its content. The risk from using it lies entirely with the user.
While using this site, you agree to have read and accepted our terms of use and privacy policy.
Copyright 1999-2009 by Refsnes Data. All Rights Reserved.