Bonjour à tous,

Je suis ici pour rechercher un peu d'aide à la résolution d'un petit problème qui je suis sûr est simple pour quelqu'un qui connait bien le javascript ou le php .

J'ai téléchargé un script d'auto-complétion que j'ai trouvé sur le web et je souhaiterais le modifier afin qu'au clique il insert 2 informations différente au lieu d'une dans un input.

Exemple recherche de ville par code postal :

je tape 75013, le script va chercher en BDD 75013 qui correspond à PARIS 13, jusque là tout va bien.

Mais au clique, il insert dans l'input seulement le code postal et non la ville qui est dans une colonne différente de la même table.

Voici mon script 'completer.js' :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/* 
 * Completer is a free script that implements an auto-completion system using AJAX technologies
 * 
 * Copyright (C) 2014  Lebleu Steve <dev@e-lless.be>
 * 
 * URL : http://scripts.e-lless.be/completer/
 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the Creative Commons Licence.
 *
 */
 
 
/**
 * Implement JSON.parse de-serialization
 * 
 * @type @exp;JSON
 */
var JSON = JSON || {};
 
JSON.parse = JSON.parse || function (str) {
 
    if (str === "") 
    {
        str = '""';
    }
 
    eval("var p =" + str + ";");
 
    return p;
};
 
/**
 * IE <= 8 document.getElementsByClassName polyfill
 * 
 * @param {string} className
 * @returns {NodeList}
 */
if (typeof document.getElementsByClassName!='function') {
    document.getElementsByClassName = function() {
        var elms = document.getElementsByTagName('*');
        var ei = new Array();
        for (i=0;i<elms.length;i++) {
            if (elms[i].getAttribute('class')) {
                ecl = elms[i].getAttribute('class').split(' ');
                for (j=0;j<ecl.length;j++) {
                    if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
                        ei.push(elms[i]);
                    }
                }
            } else if (elms[i].className) {
                ecl = elms[i].className.split(' ');
                for (j=0;j<ecl.length;j++) {
                    if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
                        ei.push(elms[i]);
                    }
                }
            }
        }
        return ei;
    }
}
 
/**
 * IE <= 8 addEventListener polyfill
 * 
 * @param {HTMLElement} element
 * @param {string} event
 * @param {function} func
 * @returns {void}
 */
function AddEvent(element, event, func) {
 
    if(element.addEventListener)
    {
        element.addEventListener(event, func, false);
    }
    else 
    {
        element.attachEvent('on' + event, func);
    }
}
 
/**
 * Polyfill for XHR implements
 * 
 * @returns {XMLHttpRequest.XMLHttpRequest|Boolean|XMLHttpRequest|ActiveXObject|ActiveXObject.ActiveXObject}
 */
function GetXmlHttpRequest() {
 
    var xhr;
 
    if(window.XMLHttpRequest)
    {
        return xhr = new XMLHttpRequest();
    }  
    else if(window.ActiveXObject) 
    {
    	var versions = [
			            "Msxml2.XMLHTTP.6.0",
			            "Msxml2.XMLHTTP.3.0",
			            "Msxml2.XMLHTTP",
			            "Microsoft.XMLHTTP"
			        ];
 
        for(var i in versions)
        {
	        try
	        {
	            return xhr = new ActiveXObject(versions[i]);
	        }
	        catch (e){} 
        }
    }
    else 
    {
        alert("Votre navigateur ne supporte pas l'objet XMLHttpRequest");
        return xhr = false;
    }
}
 
// TODO setTimeout sur l'affichage des résultats : masquer après x secondes ?
 
if(typeof Completer === 'undefined')
{
    var Completer = {
 
        ConfigPath: 'php/configurer.php',
        PHPPath: 'php/completer.php',
        Properties: [],
        Suggestions: [],
        Pointer: -1,
        PreviousValue: '',
        Focused: null,      
        Input: null,
        Result: null, 
        Response: {},
 
        /**
         * Init elements & events
         * 
         * @returns {undefined}
         */
        Init: function() {
 
            Completer.SetProperties();
 
            var result = document.createElement('div');
                result.id = "result";
                result.className = "form--lightsearch__result";
 
            this.Result = result;
 
            var searcher = document.getElementById('searcher');
                searcher.appendChild(result);
 
            this.Input = document.getElementById('autocomplete');
 
            this.EventHandlers.KeyboardNavigation(); 
            this.EventHandlers.HideResults(this.Result);
        },
 
        EventHandlers: {
 
            /**
             * Gestion of keyboard
             * 
             * @returns {undefined}
             */
            KeyboardNavigation: function() {
 
                AddEvent(Completer.Input, 'keyup', function(e) {
 
                    e = e || window.event;
 
                    var keycode = e.keyCode;
 
                    // Up/Down into Results
                    if(keycode === 38 || keycode === 40)
                    {
                        Completer.Navigation(keycode);
                    } 
                    // Write the selected item into Input
                    else if (keycode === 13)
                    {
                        Completer.InsertSuggestion();
                    }
                    else 
                    {
                        if(Completer.Input.value !== Completer.PreviousValue)
                        {
                            Completer.DisplaySuggestions(); 
                        }  
                    }
                });
            },
 
            /**
             * Hide set of results after click on body
             * 
             * @params {HTMLElement}
             * @returns {undefined}
             */
            HideResults: function(elm) {
 
                AddEvent(document.body, 'click', function() {
                    elm.style.display = 'none';
                });
            },
 
            /**
             * Set click event on Suggestions div's
             * 
             * @param {string}
             * @returns {undefined}
             */
            ClickableSuggestion: function(nameClass) {
 
                Completer.Suggestions = document.getElementsByClassName(nameClass);
 
                if(typeof Completer.Suggestions !== 'undefined')
                {
                    var numberOfSuggestions = Completer.Suggestions.length; 
 
                    if(numberOfSuggestions !== 0 && numberOfSuggestions !== null)
                    {
                        for(var i = 0; i < numberOfSuggestions; i++)
                        {
                            AddEvent(Completer.Suggestions[i], 'click', (function(i) {
                               return function() {
                                    Completer.Focused = Completer.Suggestions[i];
                                    Completer.InsertSuggestion();
                               }; 
                            })(i)); 
                        }  
                    }
                }    
            }
        },
 
        /**
         * Set properties of the screenview
         * 
         * @returns {undefined}
         */
        SetProperties: function() {
 
            var xhr = GetXmlHttpRequest();
            xhr.open('GET', Completer.ConfigPath, true);
 
            xhr.onreadystatechange = function() {
 
                if(xhr.readyState === 4 && xhr.status === 200)
                {
                    var response = xhr.responseText;
                    Completer.Properties = response.split(', ');
                }
            };
 
            xhr.send(null);
        },
 
        /**
         * Gestion of navigation into results of the request
         * 
         * @param {int} keycode
         * @returns {undefined}
         */
        Navigation: function(keycode) {
 
            if(Completer.Pointer >= -1 && Completer.Pointer <= Completer.Suggestions.length - 1)
            {
                // Pointer out of data set, before first element
                if(Completer.Pointer === -1)
                {
                    if(keycode === 40)
                    {
                        Completer.SetFocus(keycode);
                    }    
                }
                // Pointer in data set, at last element
                else if (Completer.Pointer === Completer.Suggestions.length - 1) 
                {
                    if(keycode === 38)
                    {
                        Completer.SetFocus(keycode);
                    }   
                }
                // Pointer into data set
                else 
                {
                    Completer.SetFocus(keycode);
                }
            }    
        },
 
        /**
         * Init XHR object, send the AJAX request and display Result
         * If you use another datas set, modify only this method
         * 
         * @returns {undefined}
         */
        DisplaySuggestions: function() {
 
            Completer.Result.style.display = 'block';
            Completer.Pointer = -1;
 
            var text = "",
                xhr = GetXmlHttpRequest();
 
            xhr.open('POST', Completer.PHPPath, true);
 
            xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
 
            xhr.onreadystatechange = function() {
 
                if(xhr.readyState === 4 && xhr.status === 200)
                {
                    var response = JSON.parse(xhr.responseText);     
 
                    if(response !== null)
                    {
                        Completer.Response = response;
 
                        var properties = Completer.Properties.length,
                            responseLength = response.length;
 
                        for(var i = 0; i < responseLength ; i++)
                        {
                            if(typeof response[i] !== 'undefined')
                            {
                                var cls;
 
                                i + 1 === responseLength ? cls = 'last' : cls = '';
 
                                text += "<div id=\"" + i + "\" class=\"item--result " + cls + "\">\n";
 
                                    for(var j = 0; j < properties; j++)
                                    {
                                        text += "<span class=\"data-" + j + "\">" + response[i][j] + "</span>\n";
                                    }
 
                                text += "</div>\n";
                            }  
                        }  
                    }
                    else 
                    {
                        text = "<div class=\"item--result\">Not found</div>";
                    }
                }
                else if(xhr.readyState === 4 && xhr.status !== 200)
                {
                    text = "<div class=\"item--result\">Error</div>";
                }
 
                Completer.Result.innerHTML = text;
 
                Completer.EventHandlers.ClickableSuggestion('item--result');
            };
 
            xhr.send('requestExpression=' + Completer.Input.value);    
        },
 
 
        /**
         * Insert a suggestion into Input file
         * 
         * @returns {undefined}
         */
        InsertSuggestion: function() {
 
            var id;
 
            Completer.Focused !== null ? id = Completer.Focused.id : id = 0;    
			Completer.Input.value = Completer.Response[id][0]; // Update this line with anonymous Property
            Completer.Pointer = -1;
            Completer.Result.style.display = 'none';
        },
 
        /**
         * Set focus params for keyboard Navigation
         * 
         * @param {int} keycode of the Navigation (38/40)
         * @returns {undefined}
         */
        SetFocus: function(keycode) {
 
            if(keycode === 40)
            {
                if(this.Pointer !== -1)
                {
                    Completer.RemoveFocus();
                } 
                Completer.Pointer++;
                Completer.GetFocus();
            }
            else if(keycode === 38)
            {
                Completer.RemoveFocus();
                Completer.Pointer--;
                if(Completer.Pointer !== -1)
                {
                    Completer.GetFocus();   
                }   
            }
        },
 
        /**
         * Get the focus on one element & set Focused property
         * 
         * @returns {undefined}
         */
        GetFocus: function() {
            Completer.Focused = Completer.Suggestions[Completer.Pointer]; 
            Completer.Suggestions[Completer.Pointer].className += ' focus';
        },
 
        /**
         * Remove the focus on one element & set Focused property
         * 
         * @returns {undefined}
         */
        RemoveFocus: function() {
            Completer.Focused = null;
            Completer.Suggestions[Completer.Pointer].className = 'item--result';
        }
    };
}
else 
{
    console.log('This namespace already exists !');
}
 
Completer.Init();
ainsi que le fichier php 'completer.php' :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
$request       = strip_tags($_POST['requestExpression']);   // Request expression
$filePath      = '../files/completer.json';     // Path .json file
$cfgPath       = '../files/configuration.ini';  // Path configuration file
$responseSize  = 5;                             // Number of items to return
$expire        = time() - 3600;                 // Validity cache duration in seconds
 
if(file_exists($cfgPath)) 
{
    $cfg = parse_ini_file ($cfgPath);
 
    // If the file doesn't exist or is not actualized, load the datas set on DB
    if(!file_exists($filePath) || filemtime($filePath) > $expire)
    {
        try 
        {
            $pdo = new PDO($cfg["dsn"], $cfg["user"], $cfg["pwd"], array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION , PDO::ATTR_PERSISTENT => TRUE));
        } 
        catch(PDOException $exception)
        {
            exit("Error Data Base connexion : " . $exception->getMessage());
        }
 
        $sql = ("SELECT " . $cfg["enum"] . " FROM " . $cfg["table"] . " ORDER BY ville_code_postal ASC");
        $query = $pdo->query($sql);
 
        if($query->rowCount() > 0)
        {
            while($row = $query->fetch())
            {
                $result[] = $row;
            }
 
            // Encode the result of the SQL request in JSON and puts him into JSON file
            $content = json_encode($result);
            $handle  = fopen($filePath, 'w+');
 
            if (flock($handle, LOCK_EX))
            {
                ftruncate($handle, 0);     
                fwrite($handle, $content);
                flock($handle, LOCK_UN);   
            }
            else
            {
                exit("Error Unable to lock file");
            }
 
            fclose($handle);
        }
        else 
        {
            @mail('admin@yoursite.com', 'application@yoursite.com', 'Completer.js : the SQL request return zero result');
 
            // Reply soluce
            if (file_exists($filePath))
            {
                $content = file_get_contents($filePath);
            }
        }
 
    }
    // Else if the file exist and is actualized, read it
    else if (file_exists($filePath))
    {
        $content = file_get_contents($filePath);
    }
 
    // Columns list to return
    $enum = explode(',', trim($cfg['enum']));
 
    // Decode the data source
    $complete = json_decode($content);
 
    $length = count($complete);
    for($i = 0 ; $i < $length ; $i++)
    {
        // Case unsensitive matching
        $pos = strpos(strtolower($complete[$i]->$enum[0]), strtolower($request));
 
        // One occurence is find
        if($pos !== FALSE)
        {
            // The string begin by the occurence
            if($pos == 0)
            {
                $response[] = $complete[$i];
            }
        }
    }
 
    // Alphabetic sorting
    sort($response);
 
    // Send response encoded in JSON and limited to 5 suggestions
    echo json_encode(array_slice($response, 0, $responseSize));   
}  
else 
{
    @mail('admin@yoursite.com', 'application@yoursite.com', 'Completer.js : configuration.ini is unavailable');
    exit("Unable to load configuration file");
}
?>
J'espère que vous pourrez m'aider...

Merci à vous.