· 9 years ago · Oct 28, 2016, 08:12 PM
1CREATE TABLE IF NOT EXISTS `nomes` (
2 `id` int(11) NOT NULL AUTO_INCREMENT,
3 `nome` varchar(100) NOT NULL,
4 `cidade` varchar(100) NOT NULL,
5 PRIMARY KEY (`id`)
6) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=166;
7
8class DB{
9 public function open(){
10 try{
11 return new PDO("mysql:host=localhost;dbname=autocomplete;charset=utf8", "usuario", "senha");
12 }catch(PDOException $e){
13 print_r($e);
14 }
15 }
16}
17
18<!DOCTYPE html>
19<html lang="pt-br">
20<head>
21 <title>AutoComplete - SO</title>
22 <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
23</head>
24
25<body>
26 <input id="nome" class="form-control txt-auto"/>
27
28 <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
29 <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
30 <script src="request.js"></script>
31</body>
32</html>
33
34$("#nome").autocomplete({
35 source: function(req, res) {
36 $.ajax({
37 url : 'ajax.php',
38 dataType: "json",
39 data: {
40 nome: req.term,
41 action: 'nome'
42 },
43 success: function(data) {
44 res($.map(data, function(item){
45 return{
46 label: item,
47 value: item
48 }
49 }));
50 }
51 });
52 },
53 autoFocus: true,
54 minLength: 0
55});
56
57<?php
58require_once 'conn.php';
59
60$db = new DB;
61
62if($_GET['action'] == 'nome'){
63 $sql = $db->open->query("SELECT nome FROM nomes WHERE nome LIKE '".strtoupper($_GET['nome'])."%'");
64
65 $json = array();
66
67 while ($fetch = $sql->fetchObject()) {
68 array_push($json, $fetch->nome);
69 }
70
71 echo json_encode($json);
72}
73
74?>