Introduction
Ajax is a very popular acronym these days. Who has not dreamed of being able to add the prestigious Ajax label (Asyncronimous Javascript And Xml) to one of its websites? The purpose of this article is to take back step by step the self-completion mechanism using Ajax technology implemented in many places. The most speaking, and perhaps the most successful is that of Google Suggest that offers you as you enter the text of your search the most popular completions.
For this kind of things, it is of course unthinkable to pass the loading of the web page all information to the client browsers. The volume that this would represent would saturate the server in a while record! This is where our famous magic fairy Ajax comes in, who will fetch the information from the server and integrate it into the client without it having to undergo a full reload of the page.
For this example, we will use a very basic script for the data server (a simple PHP page) because what interests us the most is obviously the implementation of all the JavaScript engine needed to operate our self-completion. In addition, the compatibility of Google Suggest with older browsers is very thorough. In order to make the scripts more readable, we will content ourselves with a version thatworks with recent browsers (IE 6, Firefox 1.5 and partially Opera 8.5).
We will create a script to manage a drop-down list, in the usual sense of the term, which will present the features that a user is entitled to expect from such a list: proposal to complete the text field, highlighting of the active suggestion, navigation using the up / down arrows or with the mouse, ... For the sake of clarity, we will implement the features of our auto-completion script gradually, in three main stages: The implementation of the client / server dialogue, the implementation of the presentation and finally event management.
Step 1 - Make the client and the server communicate
Step 1 - Make the client and the server communicate
This first step is where we are going to implement the famous xmlHttpRequest object that will help us enable our web browser to communicate with the server, without the user needing to reload his page.
This is the heart of any page using Ajax, and the novelty introduced by this technology. But for all that, this is absolutely not the most difficult part of the thing ....
The objectxmlHttpRequest
allows as its name suggests to make an HTTP request to our server (and only this one for security reasons), and to perform a processing in our page at the time of the return of the request. In our case, the request will give us the first 10 possibilities of completion of our text field.
1 .1- Server side
1 .1- Server side
First of all let's look at the server side page which will return the completion possibilities to our user. Since this is not really the subject of this article, we will reduce it to its bare minimum.
so that it returns us, for a given user input, an XML file containing the completions possible.
Here is the php file we will use:-
<? Php
header ('Content-Type: text / xml; charset = utf-8');
echo (utf8_encode ("<? xml version = '1.0' encoding = 'UTF-8'?> <options>"));
if (isset ($ _ GET ['debut'])) {
$ start = utf8_decode ($ _ GET ['start']);
} else {
$ start = "";
}
$ start = strtolower ($ start);
$ list = array ([...]);
function generateOptions ($ start, $ list) {
$ MAX_RETURN = 10;
$ i = 0;
foreach ($ list as $ element) {
if ($ i <$ MAX_RETURN && substr ($ element, 0, strlen ($ start)) == $ start) {
echo (utf8_encode ( "<option>" $ element "</ option> ')..);
$ I ++;
}
}
}
generateOptions ($ start, $ list);
echo ( "</ option>");
?>
The list of words used (in the variable $ list, which has not been copied here) is the list of 1500 words mastered by the pupils of CE2.
You can test the return of this page php: List of words beginning with "de"
.
The maximum number of possibilities returned by this page is 10. In a real application, it is quite possible consider that the most likely completions be returned first (as for Google Suggest). These treatments are the responsibility of the server and on your initiative.
The only particular point of this php page is to note that, in general, it is appropriate to send the XML response in UTF-8 very clean, to avoid possible problems of encoding by after (accents which disappear, XML document not recognized ...).
1 .2 - Client side
1 .2 - Client side
1 .2.1 - The HTML page
On the client side, we will start by setting up an HTML page, as simple as possible. She will complemented by two script tags which will link it to our javascript script and initialize this script.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<title>Test d'autocompletion</title>
</head>
<body>
<form name="form-test" id="form-test"
action="javascript:alert('soumission de ' +
document.getElementById('champ-texte').value)"
style="margin-left: 50px; margin-top:20px">
<input type="text" name="champ-texte" id="champ-texte" size="20" />
<input type="submit" id="bouton-submit">
</form>
</body>
</html
The body of the page will not change the whole article. We will just connect scripts required. Thus, for a user who has not activated Javascript (about 10% of Internet users), the form will appear as a normal form, without help to completion.
1 .2.2 - The xmlHttpRequest object
The first script we will put in place is the one to create an xmlHttpRequest object (or XHR for the close friends). This object will allow us to make requests to our server, without having to reload entirely the page. For more information about the subject and these methods, see the siddh article on the subject.
For our part, we will use the following method to create a new object, compatible between all current browsers supporting the xmlHttpRequest object :-
// return an xmlHttpRequest object.
// compatible method between all browsers (IE / Firefox / Opera)
function getXMLHTTP () {
var xhr = null;
if (window.XMLHttpRequest) // Firefox and others
xhr = new XMLHttpRequest ();
else if (window.ActiveXObject) {// Internet Explorer
try {
xhr = new ActiveXObject ("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject ("Microsoft.XMLHTTP");
} catch (e1) {
xhr = null;
}
}
}
else {// XMLHttpRequest not supported by the browser
alert ("Your browser does not support XMLHTTPRequest objects ...");
}
return xhr;
1 .2.3 - Setting up constants
To work and set up, our script will need 3 constants:
• _documentForm: the form containing our text field
• _inputField: the text field itself
• _submitButton: the submit button of our form
The initialization function of our script will take as argument a reference on these three elements
var _documentForm = null; // the form containing our text field
var _inputField = null; // the text field itself
var _submitButton = null; // the submit button of our form
function initAutoComplete (form, field, submit) {
_documentForm = form;
_inputField = field;
_submitButton = submit;
_inputField.autocomplete = "off";
}
We disable the help for entering browsers by setting the autocomplete attribute of our text field to false. This function will be linked to the window.onload event of our page. It will be enriched as and when by additional boot requirements we will encounter throughout this article.
<script type = "text / javascript">
window.onload = function () {initAutoComplete (document.getElementById ('form-test'),
document.getElementById ( 'text-field), document.getElementById (' button submit '))};
</ Script>
1 .2.4 - Check text field changes
To set up our auto-completion mechanism, we must be able to detect changes in the text field. This can not be done with the on change listener of the text field, because it is not triggered only when the field loses focus.
Detecting changes with each hit can be dangerous, for example in the case of copy / paste or other that can either go unnoticed, or saturate our poor Ajax engine with requests.
In this area again, we will take a look at Google Suggest and set up a method that periodically check for changes in the text field, and execute a query to the server if necessary.
var _oldInputFieldValue = ""; // previous value of the text field
var _currentInputFieldValue = ""; // current value of the text field
var _resultCache = new Object (); // query cache mechanism
// rotate continuously to suggest following a change in the text field
function mainLoop () {
_currentInputFieldValue = _inputField.value;
if (_oldInputFieldValue! = _ currentInputFieldValue) {
var value = escapeURI (_currentInputFieldValue);
var suggestions = _resultCache [_currentInputFieldValue];
if (suggestions) {// the answer was still
} Else {
callSuggestions (value) // remote call
}
_inputField.focus ()
}
_oldInputFieldValue = _currentInputFieldValue;
setTimeout ( "MainLoop ()", 200); // the function will retrigger in 200 ms
return true
}
This method will be called the first time in the initialization function of our script. She controls everyone of these passages the state of the text field and executes a request to the server if necessary.
_resultCache
is an object that will allow us to build a cache of queries, to avoid sending them back systematically (very useful, for example in the case of backspace).
The function metsEnPlace
will set up in the page our suggestions, and the callSuggestions
function will execute a request, via the xmlHttpRequest
object, to the data server.
The above method seems a little complex for the result, but it will undergo changes as and as steps of this article. In particular_currentInputFieldValue
will no longer be initialized inside the method but in the other methods of event management.
escapeURI
is an easy way to escape the special characters in the text field before to send the request to the server. This method is based on native JavaScript methods of browsers.
Blog Continues into next post.
Please Upvote and resteem ,If you like my post.
Posted on Utopian.io - Rewarding Open Source Contributors
Your contribution cannot be approved because it does not follow the Utopian Rules.
You can contact us on Discord.
[utopian-moderator]
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit