Ajax Asp Php
* * *
AJAX is used to create more dynamic web applications.
* * *
## AJAX ASP/PHP Example
The following example will demonstrate how a web page communicates with a web server when a user types characters in an input field: Please type letters (A - Z) in the input field below:
## Example
**Try typing the letter "a" in the input field:**
Hint:
[Try it Β»](#)
* * *
## Example Explained - The showHint() Function
When the user types characters in the input field above, the function "showHint()" is executed. This function is triggered by the "onkeyup" event:
function showHint(str){var xmlhttp; if(str.length==0){document.getElementById("txtHint").innerHTML=""; return; }if(window.XMLHttpRequest){xmlhttp=new XMLHttpRequest(); }else{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/gethint.php?q="+str,true); xmlhttp.send(); }
Source code analysis:
If the input field is empty (str.length==0), the function clears the content of the **txtHint** placeholder and exits the function.
If the input field is not empty, the showHint() function performs the following tasks:
* Creates an **XMLHttpRequest** object
* Executes a function when the server response is ready
* Sends the request to a file on the server
* Note that we add a parameter q (containing the content of the input field) to the URL
* * *
## AJAX Server Page - ASP and PHP
The server page called by the JavaScript in the above example is a PHP file named **gethint.php**.
Below, we have created two versions of the server file, one written in ASP and the other in PHP.
## ASP File
The source code in "gethint.asp" checks an array of names and returns the corresponding names to the browser:
0 if len(q)>0 then hint="" for i=1 to 30 if q=ucase(mid(a(i),1,len(q))) then if hint="" then hint=a(i) else hint=hint & " , " & a(i) end if end if next end if 'Output "no suggestion" if no hint were found 'or output the correct values if hint="" then response.write("no suggestion") else response.write(hint) end if %>
* * *
## PHP File
The code below is written in PHP and does the same thing as the ASP code above.
0if (strlen($q) > 0){ $hint=""; for($i=0; $i
YouTip