YouTip LogoYouTip

Ajax Database

AJAX Database

AJAX Database

AJAX can be used for dynamic communication with a database.

AJAX Database Example

The following example will demonstrate how a web page can read information from a database using AJAX: Please select a customer from the dropdown list below:

Example

Select a customer: Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquería Around the Horn Berglunds snabbköp Blauer See Delikatessen Blondel père et fils Bólido Comidas preparadas Bon app' Bottom-Dollar Markets B's Beverages Cactus Comidas para llevar Centro comercial Moctezuma Chop-suey Chinese Comércio Mineiro Consolidated Holdings Drachenblut Delikatessen Du monde entier Eastern Connection Ernst Handel Familia Arquibaldo FISSA Fabrica Inter. Salchichas S.A. Folies gourmandes Folk och fä HB Frankenversand France restauration Franchi S.p.A. Furia Bacalhau e Frutos do Mar Galería del gastrónomo Godos Cocina Típica Gourmet Lanchonetes Great Lakes Food Market GROSELLA-Restaurante Hanari Carnes HILARION-Abastos Hungry Coyote Import Store Hungry Owl All-Night Grocers Island Trading Königlich Essen La corne d'abondance Laughing Bacchus Wine Cellars Lehmanns Marktstand Let's Stop N Shop LILA-Supermercado LINO-Delicateses Lonesome Pine Restaurant Magazzini Alimentari Riuniti Maison Dewey Mère Paillarde Morgenstern Gesundkost North/South Océano Atlántico Ltda. Old World Delicatessen Ottilies Käseladen Paris spécialités Pericles Comidas clásicas Piccolo und mehr Princesa Isabel Vinhos Que Delícia Queen Cozinha QUICK-Stop Rancho grande Rattlesnake Canyon Grocery Reggiani Caseifici Ricardo Adocicados Richter Supermarkt Romero y tomillo Santé Gourmet Save-a-lot Markets Seven Seas Imports Simons bistro Spécialités du monde Split Rail Beer & Ale Suprêmes délices The Big Cheese The Cracker Box Toms Spezialitäten Tortuga Restaurante Tradição Hipermercados Trail's Head Gourmet Provisioners Vaffeljernet Victuailles en stock Vins et alcools Chevalier Vittero Wandtjewerk Wartian Herkku Wellington Importadora White Clover Markets Wilman Kala Wolski Zajazd

Customer info will be listed here...

Try it yourself »

Example Explained - The showCustomer() Function

When a user selects a customer in the dropdown list above, a function called "showCustomer()" is executed. This function is triggered by the "onchange" event:

function showCustomer(str) {
  var xmlhttp;
  if (str == "") {
    document.getElementById("txtHint").innerHTML = "";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
    }
  };
  xmlhttp.open("GET","/try/ajax/getcustomer.php?q="+str,true);
  xmlhttp.send();
}

The showCustomer() function does the following:

  • Check if a customer is selected
  • Create an XMLHttpRequest object
  • Create the function to execute when the server response is ready
  • Send the request off to a file on the server
  • Notice that we add a parameter q to the URL (with the content of the input field)

AJAX Server Page

The server page called by the JavaScript above is a PHP file called "getcustomer.php".

It is easy to write a server file in PHP, or with other server languages. Let's look at the corresponding example in PHP.

The source code in "getcustomer.php" does a query on a database, and returns the result in an HTML table:

<%
response.expires=-1
sql="SELECT * FROM CUSTOMERS WHERE CUSTOMERID="
sql=sql & "'" & request.querystring("q") & "'"

set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs=Server.CreateObject("ADODB.recordset")
rs.Open sql,conn

response.write("<table>")
do until rs.EOF
  for each x in rs.Fields
    response.write("<tr><td><b>" & x.name & "</b></td>")
    response.write("<td>" & x.value & "</td></tr>")
  next
  rs.MoveNext
loop
response.write("</table>")
%>

AJAX ASP/PHP

AJAX XML

ByteDance Coding Plan

Supports mainstream large models like Doubao, GLM, DeepSeek, Kimi, MiniMax. Official supply, stable and reliable.

Configuration Guide

¥9.9 / month

Activate Now

iFlytek Star Coding Plan

Includes free model call quotas. DeepSeek, GLM, Kimi, MiniMax. One-stop experience and deployment platform.

Configuration Guide

¥3.9 / month

Activate Now

← Ajax XmlfileAjax Asp Php →