PHP and AJAX Suggest

|  | 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 Suggest

## AJAX Suggest

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 web form.

## Type a Name in the Box Below

First Name:

Suggestions:

This example consists of three pages:

- a simple HTML form
- a JavaScript
- a PHP page

## The HTML Form

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

    <html>
    <head>
    <script src="clienthint.js"></script>
    </head>

    <body>

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

    <p>Suggestions: <span id="txtHint"></span></p>

    </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 showHint() is executed.
3. Below the form is a <span> called "txtHint". This is used as a placeholder for the return data of the showHint() function.

## The JavaScript

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

    var xmlHttp;

    function showHint(str)
    {
    if (str.length==0)
      {
      document.getElementById("txtHint").innerHTML="";
      return;
      }
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null)
      {
      alert ("Browser does not support HTTP Request");
      return;
      }
    var url="gethint.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("txtHint").innerHTML=xmlHttp.responseText;
     }
    }

    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 showHint() Function

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

If there is some input in the text field (str.length > 0) 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

If the input field is empty, the function simply clears the content of the txtHint placeholder.

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.

The GetXmlHttpObject() Function

AJAX applications can only run in web browsers with complete XML support.

The code above called a function called GetXmlHttpObject().

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

This is explained in the previous chapter.

## The PHP Page

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

The code in the "gethint.php" checks an array of names and returns the corresponding names to the client:

    <?php
    // Fill up 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=$_GET["q"];

    //lookup all hints from array if length of q>0
    if (strlen($q) > 0)
    {
    $hint="";
    for($i=0; $i<count($a); $i++)
      {
      if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
        {
        if ($hint=="")
          {
          $hint=$a[$i];
          }
        else
          {
          $hint=$hint." , ".$a[$i];
          }
        }
      }
    }

    //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. Find a name matching the characters sent from the JavaScript
2. If more than one name is found, include all names in the response string
3. If no matching names were found, set response to "no suggestion"
4. If one or more matching names were found, set response to these names
5. The response is sent to the "txtHint" placeholder

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

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
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 or Top of Page |  | 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.