<?php // Function to return a random number between 0 and $n-1: function R($n) { return rand() % $n; } $match = isset($_GET['match'])? $_GET['match'] : null; // Loads the words of the dictionary into the $words array: $words = Array(); $f = fopen("/usr/dict/words", "r"); for($i=0; $s = fgets($f); $i++) { // trim() removes any whitespace from the beginning and end of a string: $words[$i] = trim($s); } if ($match) { $len=strlen($match); $ret = Array(); $ridx = 0; for($i=0; $i < count($words); $i++) { // If $match matches the first $len characters of $words[$i] then add it: if (strncmp($words[$i],$match,$len) == 0) { $ret[$ridx++] = $words[$i]; // Stop after 10 words: if ($ridx > 9) break; } } } else { // Seed the Pseudo-random number generator: srand(); // Get a random word as the scripts "return" value: $ret = $words[R(count($words))]; } // $ret holds the data to be JSON encoded and "printed", i.e. returned to the // loadurl() function on the JavaScript side, be it a string or array: echo json_encode($ret); ?>
<!DOCTYPE html> <html> <head> <title> Async example </title> <meta charset='ascii'> <style> #output { border: 1px solid black; min-height: 50px; width: 300px; } </style> <script> function loadurl(url, callback) { var req = new XMLHttpRequest(); req.open("GET", url, true); req.overrideMimeType('text/plain; charset=x-user-defined'); req.onreadystatechange = function() { if (req.readyState == 4 && req.status == 200) callback(JSON.parse(req.responseText)); } req.send(null); } // Function to fill the datalist element with options: function key(ev, e) { // Probably not necessary, but avoid doing anything on arrow keys or backspace: if (ev.charCode == 0 && ev.keyCode != 8) return; // Sets the function to run after 1ms, this allows the input event to propagate // all the way though the browser and allow the input's value to be updated. setTimeout(function() { console.log("key event fired.", e.value); // If the value is empty, just reset the datalist element: if (e.value.length == 0) { var list = document.getElementById("list"); list.innerHTML = ""; return; } // Use the match GET value to specify the word prefix to match against: loadurl("words.php?match="+e.value, function(data) { console.log("loadfile callback called.", data); var list = document.getElementById("list"); var s = ""; for(i=0; i < data.length; i++) { s += "<option>" + data[i] + "</option>"; } list.innerHTML = s; }); },1); } // This function gets a random word from words.php and places it in the // 'output' div element. Called when the button is clicked on. function getword() { loadurl("words.php", function(data) { var output = document.getElementById("output"); output.innerHTML = data; }); } </script> </head> <body> <input list='list' oninput='key(event, this);' type='text' id='input'> <datalist id='list'> </datalist> <div id='output'></div> <input type='button' onclick='getword();' value='Get'> </body> </html>