Thursday, November 22, 2007

PHP, AJAX auto complete text field

Original Source:
http://wiseguysonly.com/2006/04/14/ajax-autocompletion-for-the-impatient/

Ingredients:

  1. The Scriptaculous Javascript libraries.
  2. An (X)HTML web document
  3. A textfield with and id (for this example id='search')
  4. A hidden div with an id (for this example id='auto_complete')
  5. A script to query a database written in the server-side language of your choice (for this example server.php).
  6. A database of your choice.

Step One - creating the user interface:

  • Include the lib/prototype.js and src/scriptaculous.js and src/controls.js (1) files in the head of your (X)HTML web document (2)
  • Insert your textfield (3) into the body of your (X)HTML document (2).
  • Below your textfield (3) embed some JavaScript in script tags to call a function from our included scriptaculous scripts (1):

    new Ajax.Autocompleter(”search”,”hint”,”server.php”);

  • The three arguments for our new Autocompleter wrapper are: the id of the textfield to observe; the id of the hidden div which will contain autocompletion hints; the script that will be called upon to provide the list of hints in the background.

Step two: Creating the server script.

  • Include or write whatever you need to in order to connect to your database.
  • Write your SQL to search the database for terms that are LIKE whatever is contained in the POST variable related to your textfield. In my case I gave my textfield the name 'search_item' (the same value as the id for ease).
  • Here is an example of ...SQL in php:
    • $sql = SELECT title FROM tablename WHERE title ILIKE ‘%”.$_POST[’search_item’].”%’”;
  • Output an unordered list in the server file with one list item for each result. The server file should only output this list and no other markup.

That is all you need to do. Providing you implemented that framework correctly and filled in the gaps correctly using your own server side scripting language you should be in business with an autocompletion field.


Example content of :: autocomplete.html



<div>
<label>
Type here</label>
<input type="text" id="search" name="search">
</div>
<div id="hint">
</div>
<script type="text/javascript">
new Ajax.Autocompleter("search","hint","server.php");
</script>

Example content of :: server.php

 
$sql = "SELECT title FROM autocomplete_demo
WHERE title LIKE '%" . $_POST['search'] . "%'";
$rs = mysql_query($sql);
?>
<ul>
<? while($data = mysql_fetch_assoc($rs)) { ?>
<li><? echo stripslashes($data['title']);?></li>
<? } ?>
</ul>

Centos 7 reset root/ any user lost password / lockout due to cant remember password

1. Need to be in front of the terminal. (Physically if not vm). 2. Reboot the server 3. Press 'e' in the GRUB2 boot screen. 3. bunch...