Я хочу создать поле формы, которое идентифицирует введенное имя пользователя, совпадает ли оно с существующими в массиве PHP, и выдает вывод на основе этого ниже поля ввода в виде сообщения. В основном похож на предложения Google в панели поиска.
Появляется следующее дерево решений
<response>
<br/>
<font size="1">
<table class="xdebug-error xe-notice" dir="ltr" border="1" cellspacing="0" cellpadding="1">
<tr>
<th align="left" bgcolor="#f57900" colspan="5">
<span style="background-color: #cc0000; color: #fce94f; font-size: x-large;">( ! )</span>
Notice: Undefined index: name in C:\wamp64\www\AJAX\ajax.php on line
<i>8</i>
</th>
</tr>
<tr>
<th align="left" bgcolor="#e9b96e" colspan="5">Call Stack</th>
</tr>
<tr>
<th align="center" bgcolor="#eeeeec">#</th>
<th align="left" bgcolor="#eeeeec">Time</th>
<th align="left" bgcolor="#eeeeec">Memory</th>
<th align="left" bgcolor="#eeeeec">Function</th>
<th align="left" bgcolor="#eeeeec">Location</th>
</tr>
<tr>
<td bgcolor="#eeeeec" align="center">1</td>
<td bgcolor="#eeeeec" align="center">0.0007</td>
<td bgcolor="#eeeeec" align="right">405048</td>
<td bgcolor="#eeeeec">{main}( )</td>
<td title="C:\wamp64\www\AJAX\ajax.php" bgcolor="#eeeeec">
...\ajax.php
<b>:</b>
0
</td>
</tr>
</table>
</font>
We need your name. Please enter your name!
</response>
Мой html код (индекс. html) просто включает только это поле. Это показано ниже.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Ajax Example</title>
<script type="text/javascript" src="ajax-js.js"></script>
<style type="text/css">
p{
font-size:1em;
}
</style>
</head>
<body onload="process()">
<!-- a button is not used here because the goal is to get data in php file while typing -->
<p>Please enter your name: </p>
<input type="text" id="username"/>
<div id="message"></div>
</body>
</html>
Мой js файл (ajax - js. js) показан ниже.
//As we want to know XMLHttp Request is formed in other functions we initialize a global variable for it.
var xmlHttp= createXmlHttpRequest();
//function to make XMLhttp request
function createXmlHttpRequest(){
//this function returns a boolean value if it can make the XMLhttp object
var xmlHttp;
//to check IE5 or IE6 can handle this as these handle XMLHttp request are different
if(window.ActiveXObject){
//we check whether it can initialize ActiveXObject which is responsible to XMLHttp request
try
{
xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp=false;
}
}
else{ //to check for other browsers like mozilla & chrome
try
{
xmlHttp= new XMLHttpRequest();
}
catch(e)
{
xmlHttp=false;
}
}
if(!xmlHttp){
alert("Error creating XMLHttpRequest Object.");
}
else{
return xmlHttp;
}
}
//function to process XMLhttp request(sending request properly to server)
function process(){ //this is the function we load to HTML
//(therefore onload is added to HTML body)
//to call this function when loading HTML body
//this is the function processed when loading HTML document
if(xmlHttp.readyState== 4 || xmlHttp.readyState== 0){ //this readyStete is used to check whether request is busy due to internet being slow or server being slow and not going (value 4 corresponds to whether it goes properly) there
name= encodeURIComponent(document.getElementById("username").value); //encodeURIComponent function used to encode username text to a suitable format
xmlHttp.open("GET","ajax.php?name="+name,true); //use GET method and send username text as name parameter to php file
xmlHttp.onreadystatechange= handleServerResponse ; //onreadystatechange event takes handleServerResponse() function return value
xmlHttp.send(null); //send method used to send the request to php file
}
else
setTimeout('process()',1000); //to retry this process after 1000ms if server is busy or unavailable
}
//function to handle response from php file in server
function handleServerResponse(){
//this function adjust XML response from php file to HTML format
if(xmlHttp.readyState== 4 ){ //to check xmlHttp response readyState property whether response goes there
if(xmlHttp.status== 200){ //status property becomes 200 if request goes there and server response okay
var xmlResponse=xmlHttp.responseXML; //responseXML element is the XML data we get from server as response
var xmlDocumentElement=xmlResponse.documentElement;//documentElement element is the part we want from response
var helloMessage=xmlDocumentElement.firstChild.data;//firstChild.data is the tag(data from XML element) in documentElement that we wants
document.getElementById("message").innerHTML='<strong>'+ //we put those data in helloMessage, within <div> tag of the
hellowMessage+'</strong>'; //of HTML document refering to it's id (strong tags are used in HTML to seperate text from rest of the content)
setTimeout('process()',1000); //retry in case internet connection drops
}
else{
alert("There was a problem in the server. "+xmlHttp.statusText);
} //statusText property tells what's the problem
}
}
Файл PHP ( ajax. php) показано ниже.
<?php
//as php file's response should be in XML first we have to include XML format to the php file
//for that we use php header function to set format of php file output
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>'; //setting xml parameters
echo '<response>'; //creating xml tag for response
$name = $_GET['name']; //to store the GET query string in a variable
$username = array('MAHESH','SANJAYA','NISHANTHA','DAVID','SANATH','SUMITH');
if(in_array(strtoupper($name),$username)){ //to check whether the input name matches with elements in the array
//strtoupper used to eliminate problem of a letter being lowercase in input that hinders comparison
echo 'Hellow, Welcome '.htmlentities($name).'!';
//htmlentities() is used to encode html characters present in the $name
// ex. if there is a space prsent it's converted to a html character
}
else if(trim($name =='')){ //once whitespaces are removed from trim and still empty user has not entered anything
echo'We need your name. Please enter your name!';
}
else{ //else to account when no match found
echo htmlentities($name).' , You are not a member.';
}
echo '</response>';
?>