Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Primordiale esempio di autocomplete PHP & MySQL + AJAX
- PHP (result.php):
- //RICEVO LA CHIAVE DI RICERCA
- //controllo che esista altrimenti termino l'esecuzione dello script
- if ( isset($_REQUEST['key']) && $_REQUEST['key'] != "" ){
- $key = $_REQUEST['key'];
- }else{
- exit;
- }
- //RICEVO I DATI DAL DB
- //eseguo una query sul database MySQL, se è in uso un database se no si può sostituire questa parte con codice diverso
- $query = "SELECT * FROM table WHERE name LIKE '%" . $key . "%';";
- $res = mysql_query($query) or die(mysql_error());
- //controllo che il numero di dati non sia zero altrimenti termino l'esecuzione dello script
- if ( mysql_num_rows($res) <= 0 ){
- exit;
- }
- //USANDO XML
- //genero l'output in XML
- echo "<?xml version=\"1.0\" ?>\n<xml>\n";
- for ( $i = 0 ; $i < mysql_num_rows($res) ; $i++ ){
- echo "\t<result>\n";
- echo "\t\t<name>" . mysql_result($res, $i, 'name') . "</name>\n";
- echo "\t</result>\n";
- }
- echo "</xml>";
- //USANDO JSON
- //genero l'output in JSON
- echo '{"result":[';
- for ( $i = 0 ; $i < mysql_num_rows($res) ; $i++ ){
- if ( $i == 0 ){
- echo '{"name":"' . mysql_result($res, $i, 'name') . '"}';
- }else{
- echo ',{"name":"' . mysql_result($res, $i, 'name') . '"}';
- }
- }
- echo ']}';
- JAVASCRIPT:
- function getData(){
- //ottengo il testo inserito nel campo input
- var key = $("#input-id").val();
- //controllo che non sia vuoto altrimenti termino lo script
- if ( key == "" ){
- return false;
- }
- //genero l'URL con l'eventuale parametro GET
- var url = "result.php?key=" + key;
- var append = "";
- //eseguo la chiamata AJAX alla pagina PHP
- $.ajax({
- url: url,
- success: function(data){
- //ricevo i dati dalla pagina PHP
- //controllo che i dati non siano vuoti altrimenti termino lo script
- if ( data == "" ){
- return false;
- }
- //svuoto il contenitore HTML
- $("#html-ul-id").html("");
- //USANDO XML
- $(data).find('result').each(function(){
- //per ogni risultato appendo al contenitore HTML il markup
- append = '<li>' + $(this).find('name').text() + '</li>';
- $("#html-ul-id").append(append);
- });
- //USANDO JSON
- var obj = JSON.parse(data);
- for ( var i = 0 ; i < obj.result.length ; i++ ){
- //per ogni risultato appendo al contenitore HTML il markup
- append = '<li>' + obj.result[i].name + '</li>';
- $("#html-ul-id").append(append);
- }
- return true;
- }
- });
- }
- //per ogni pressione di un tasto sulla tastiera eseguo la funzione di ricerca
- $("#input-id").keyup(function(){
- getData();
- });
Advertisement
Add Comment
Please, Sign In to add comment