Précédent   Forum des professionnels en informatique > Webmasters - Développement Web > JavaScript > Bibliothèques & Frameworks > jQuery
jQuery Forum d'entraide sur le framework jQuery. Avant de poster : Tutoriels jQuery, FAQ jQuery, Tous les tutoriels JavaScript, Toutes les FAQ JavaScript
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Réponse Proposer ce sujet en actualité
 
Outils de la discussion
Publicité
'
Vieux 23/01/2012, 15h08   #1
Membre du Club
 
Avatar de fazpedro
 
Homme
Inscription : août 2009
Messages : 360
Détails du profil
Informations personnelles :
Sexe : Homme
Localisation : France

Informations forums :
Inscription : août 2009
Messages : 360
Points : 64
Points : 64
Par défaut Jquery ui autocomplete source php

Bonjour,

j'ai lu beaucoup de choses sur le plugin autocomplete (que j'ai réussi à faire fonctionner avec des variables fixes...), mais je n'arrive pas à créer correctement un fichier PHP source pour récupérer mes données de façon dynamique...

le script dans le "head" :
Code :
1
2
3
4
5
6
7
<script>
$(document).ready(function() {
$(function() 	{
					$( "#tags" ).autocomplete({	source: "recherche.php", minLength: 2 });
				});
		});
</script>
recherche.php :
Code :
1
2
3
4
5
6
7
8
9
10
11
<?php 
require('configuration.php');
$sql = connect_sql();
$q = $_GET['q'];
$sql2 = mysql_query("SELECT nom FROM evenement WHERE nom LIKE '$q%' ";
while($tmp = mysql_fetch_assoc($sql2))
	{
		$res[] = array	(	'nom' => $tmp['nom']	);
	}
echo json_encode($res);
?>
il ne se passe rien quand je tape dans l'input "tags" :
Code :
1
2
3
4
5
6
7
8
<div class="ui-widget">
	<span onmouseover="_tipon(this)" onmouseout="_tipoff()">
	<span class="google-src-text" style="direction: ltr; text-align: left">
	<label for="tags">Nom :</label>
	</span>
	</span>
	<input id="tags" tabindex="1" name="recherche" />
	</div>
dans le résultat de "recherche.php", voici ce que j'ai :
Code :
[{"nom":"Premier"},{"nom":"Deuxieme"},{"nom":"troisieme"},....]

Merci d'avance !
fazpedro est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 30/01/2012, 12h40   #2
Membre régulier
 
Avatar de flotho
 
Homme Florent THOMAS
Architecte de système d'information
Inscription : novembre 2006
Messages : 130
Détails du profil
Informations personnelles :
Nom : Homme Florent THOMAS
Localisation : France, Pyrénées Orientales (Languedoc Roussillon)

Informations professionnelles :
Activité : Architecte de système d'information

Informations forums :
Inscription : novembre 2006
Messages : 130
Points : 87
Points : 87
Envoyer un message via Skype™ à flotho
Bonjour,

essayez :
Chez moi cela a donné du mieux
__________________
Créateur www.kipigo.com
Fondateur www.tdeo.fr
Linux | Java | J2EE | NB Platform | Pentaho | PostgreSQL
flotho est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 30/01/2012, 15h39   #3
Membre du Club
 
Avatar de fazpedro
 
Homme
Inscription : août 2009
Messages : 360
Détails du profil
Informations personnelles :
Sexe : Homme
Localisation : France

Informations forums :
Inscription : août 2009
Messages : 360
Points : 64
Points : 64
en fait, il recherche mais ne me propose rien...
je ne vois pas où ça coince ?
Merci.

html :
Code :
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
<?php require('configuration.php');$sql = connect_sql();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />	
<meta name="robots" content="noindex, nofollow" />
<title><?php echo $nom_site ?></title>
<link rel="Stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/base/jquery-ui.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.ui/1.8.10/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$(function() 	{
					$("input#tags").autocomplete({	source: "recherche.php", minLength: 2 });
					// $("#tags").autocomplete({	source: "recherche.php", minLength: 2 });
				});
		});
</script>
</head>
<body>
<div id="mainContent">
<br />
<p>recherche essai autocomplete </p>
<div class="ui-widget">
<span onmouseover="_tipon(this)" onmouseout="_tipoff()">
<span class="google-src-text" style="direction: ltr; text-align: left">
<label for="tags">Nom :</label>
</span>
</span>
<input id="tags" tabindex="1" name="recherche" />
</div>
</body>
</html>
recherche.php :
Code :
1
2
3
4
5
6
7
8
9
10
11
<?php 
require('configuration.php');
$sql = connect_sql();
$q = $_GET['q'];
$sql2 = mysql_query("SELECT nom FROM evenement WHERE nom LIKE '$q%' ");
while($tmp = mysql_fetch_assoc($sql2))
	{
		$res[] = array	(	'nom' => $tmp['nom']	);
	}
echo json_encode($res);
?>
fazpedro est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 30/01/2012, 15h50   #4
Membre régulier
 
Avatar de flotho
 
Homme Florent THOMAS
Architecte de système d'information
Inscription : novembre 2006
Messages : 130
Détails du profil
Informations personnelles :
Nom : Homme Florent THOMAS
Localisation : France, Pyrénées Orientales (Languedoc Roussillon)

Informations professionnelles :
Activité : Architecte de système d'information

Informations forums :
Inscription : novembre 2006
Messages : 130
Points : 87
Points : 87
Envoyer un message via Skype™ à flotho
Ok,

Je commence à comprendre. Je vais te proposer quelquechose sous couvert des experts de ce forum.

Tu cherches à accéder à une page "recherche.php" qui contient un code dynamique!

Donc l'auto complète ne te renverra rien. A ta place je travaillerai avec de l'ajax.
La source officielle : http://jqueryui.com/demos/autocomplete/#xml
propose que la source de donnée soit déja alimentée ce qui ne sera pas le cas pour toi.

Il faut donc intégrer l'appel à la source de données comme fonction dans le paramètre source de ton autocomplete. En me basant sur :http://stackoverflow.com/questions/4...ote-xml-source j'ai obtenu le code suivant qui est fonctionnel chez moi :
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$( "input#quoi" ).autocomplete({
            source: function(request, response){
                $.ajax({
                    url: "tonurl.php", 
                    dataType: "xml",
                    data: {input:request["term"]},
                    success: function( xmlResponse ) {                         
                        response( 
                        $( "rs", xmlResponse ).map(function() {
                            return {
                                value:  __highlight($( "libellenormalized", this ).text(), request.term) ,                                
                                desc:   $( "info", this ).text() ,
                                id: $( "id", this ).text()
                            };
                        }))
                    },
                    error: function() {
                        alert("XML File could not be found");
                    }
                });              
            });
En gras un point pour lequel j'ai pas mal galéré.

Une ressource à laquelle tu arriveras bien au final pour faire du highlight : http://forum.jquery.com/topic/autoco...bold-highlight

Bon courage
__________________
Créateur www.kipigo.com
Fondateur www.tdeo.fr
Linux | Java | J2EE | NB Platform | Pentaho | PostgreSQL
flotho est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 30/01/2012, 22h15   #5
Membre du Club
 
Avatar de fazpedro
 
Homme
Inscription : août 2009
Messages : 360
Détails du profil
Informations personnelles :
Sexe : Homme
Localisation : France

Informations forums :
Inscription : août 2009
Messages : 360
Points : 64
Points : 64
Aucun résultat... j'ai beau regarder sur le net, je ne trouve pas la solution pour récupérer les données dans l'input...

html :
Code :
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
<?php require('configuration.php'); 
$sql = connect_sql();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />	
<meta name="robots" content="noindex, nofollow" />
<title><?php echo $nom_site ?></title>
<link rel="Stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/base/jquery-ui.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.ui/1.8.10/jquery-ui.js"></script>
<script>
	$(document).ready(function() {
		$( "input#tags" ).autocomplete({
			source: function(request, response) {      
				$.ajax({
					url: "recherche.php",
					dataType: 'json',
					data: { q: request.term },
					success: function(data) {
						response($.map(data, function(item) {
						return {label: __highlight(item.title, request.term) + " (" + item.type + ")",                    
						value: item.title};          }));        }      }); 
						   },
						 minLength: 2)  
						});
</script>
 
</head>
<body>
<div id="mainContent">
<br />
<p>recherche essai autocomplete </p>
<div class="ui-widget">
<span onmouseover="_tipon(this)" onmouseout="_tipoff()">
<span class="google-src-text" style="direction: ltr; text-align: left">
<label for="tags">Nom :</label>
</span>
</span>
<input id="tags" tabindex="1" name="recherche" />
</div>
</body>
</html>
recherche.php :
Code :
1
2
3
4
5
6
7
8
9
10
11
<?php 
require('configuration.php');
$sql = connect_sql();
$q = $_GET['q'];
$sql2 = mysql_query("SELECT nom FROM evenement WHERE nom LIKE '$q%' ");
while($tmp = mysql_fetch_assoc($sql2))
	{
		$res[] = array	(	'nom' => $tmp['nom']	);
	}
echo json_encode($res);
?>
fazpedro est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 31/01/2012, 00h24   #6
Rédacteur
 
Avatar de danielhagnoul
 
Homme Daniel Hagnoul
Étudiant perpétuel
Inscription : février 2009
Messages : 3 221
Détails du profil
Informations personnelles :
Nom : Homme Daniel Hagnoul
Âge : 61
Localisation : Belgique

Informations professionnelles :
Activité : Étudiant perpétuel
Secteur : Enseignement

Informations forums :
Inscription : février 2009
Messages : 3 221
Points : 6 767
Points : 6 767
Bonsoir

http://jqueryui.com/demos/autocomplete/#remote

Citation:
$( "#tags" ).autocomplete({ source: "recherche.php", minLength: 2 });
Il n'y pas de méthode select : voir le source de l'exemple.
__________________

FAQ jQuery

Mon cahier d’exercices sur jQuery & Co

Si un message vous a aidé ou vous semble pertinent, votez pour lui !
danielhagnoul est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 31/01/2012, 09h49   #7
Membre du Club
 
Avatar de fazpedro
 
Homme
Inscription : août 2009
Messages : 360
Détails du profil
Informations personnelles :
Sexe : Homme
Localisation : France

Informations forums :
Inscription : août 2009
Messages : 360
Points : 64
Points : 64
en indiquant ceci :
Code :
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
<?php require('configuration.php');$sql = connect_sql();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />	
<meta name="robots" content="noindex, nofollow" />
<title><?php echo $nom_site ?></title>
<style>.ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }</style>
<link rel="stylesheet" href="jquery_mobile.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.ui/1.8.10/jquery-ui.js"></script>
<script>
$(function() {
		function log( message ) {
			$( "<div/>" ).text( message ).prependTo( "#log" );
			$( "#log" ).scrollTop( 0 );
		}
		$( "#tags" ).autocomplete({
			source: function( request, response ) {
				$.ajax({
					url: "http://ws.geonames.org/searchJSON",
					dataType: "jsonp",
					data: {
						featureClass: "P",
						style: "full",
						maxRows: 12,
						name_startsWith: request.term
					},
					success: function( data ) {
						response( $.map( data.geonames, function( item ) {
							return {
								label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
								value: item.name
							}
						}));
					}
				});
			},
			minLength: 2,
			select: function( event, ui ) {
				log( ui.item ?
					"Selected: " + ui.item.label :
					"Nothing selected, input was " + this.value);
			},
			open: function() {
				$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
			},
			close: function() {
				$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
			}
		});
	});
	</script>
</head>
<body>
<div id="mainContent">
<br />
<div class="demo">
<div class="ui-widget">
<label for="tags">Recherche ici : </label>
<input id="tags" />
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
</div><!-- End demo -->
</div>
</body>
</html>
Cela fonctionne bien, mais en indiquant mon url "recherche.php" cela ne fonctionne pas !

c'est donc ce code qui doit être erroné mais je ne vois pas où ?
merci.

recherche.php :
Code :
1
2
3
4
5
6
7
8
9
10
11
12
 
<?php 
require('configuration.php');
$sql = connect_sql();
$q = $_GET['q'];
$sql2 = mysql_query("SELECT nom FROM evenement WHERE nom LIKE '$q%' ");
while($tmp = mysql_fetch_assoc($sql2))
	{
		$res[] = array	('nom' => $tmp['nom']);
	}
echo json_encode($res);
?>
fazpedro est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 13/02/2012, 15h27   #8
Membre du Club
 
Avatar de fazpedro
 
Homme
Inscription : août 2009
Messages : 360
Détails du profil
Informations personnelles :
Sexe : Homme
Localisation : France

Informations forums :
Inscription : août 2009
Messages : 360
Points : 64
Points : 64
j'ai modifié et j'arrive presque à avoir un résultat...

html :
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.autocomplete.min.js"></script>
<link rel="stylesheet" href="jquery.autocomplete.css" type="text/css" />
</head>
 
<body>
<p>Recherche :<br /><br />
<input type="text" style="width: 800px;" value="" id="Tags" class="ac_input"/>
</p>
<script type="text/javascript">
  function findValue(li) {
  	if( li == null ) return alert("No match!");		// if coming from an AJAX call, let's use the CityId as the value
  	if( !!li.extra ) var sValue = li.extra[0];		// otherwise, let's just display the value in the text box
  	else var sValue = li.selectValue;				// alert("The value you selected was: " + sValue);
	}
  function selectItem(li) {findValue(li);}
  function formatItem(row) {return row[0] + " (id: " + row[1] + ")";}
  function lookupLocal(){var oSuggest = $("#Tags")[0].autocompleter;oSuggest.findValue();return false;}
    $("#Tags").autocomplete("recherche.php",
	{delay:10,minChars:1,
	// matchSubset:1,matchContains:1,cacheLength:10,
	onItemSelect:selectItem,onFindValue:findValue,formatItem:formatItem,autoFill:true}
    );
</script>
recherche.php :
Code :
1
2
3
4
5
6
7
8
9
10
11
12
<?php 
require('configuration.php');
$sql = connect_sql();
$q = strtolower($_GET["q"]);
if (!$q) return;
$sql2 = mysql_query("SELECT nom FROM evenement WHERE nom LIKE '$q%' ");
while($tmp = mysql_fetch_assoc($sql2))
	{
		$res[] = array($tmp['nom']);
	}
echo json_encode($res);
?>
le résultat quand je tape le début du nom :
[["nom1"]],[["nom2"]]...(id:undefined)

j'y suis presque, c'est mon fichier "recherche.php" qui n'est pas encore au point, non ?
peut-être le format JSON qui n'est pas bon ?

Merci de votre aide !
fazpedro est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 15/02/2012, 15h43   #9
Membre du Club
 
Avatar de fazpedro
 
Homme
Inscription : août 2009
Messages : 360
Détails du profil
Informations personnelles :
Sexe : Homme
Localisation : France

Informations forums :
Inscription : août 2009
Messages : 360
Points : 64
Points : 64
Bonjour,

j'ai enfin réussi !

Voici les codes complets :

HTML :
Code :
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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />	
<meta name="robots" content="noindex, nofollow" />
<title>ESSAI AUTOCOMPLETE</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.autocomplete.min.js"></script>
<link rel="stylesheet" href="jquery.autocomplete.css" type="text/css" />
</head>
<body>
<p>Recherche :<br /><br />
<input type="text" style="width: 400px;" value="" id="Tags" class=".ac_results" autocomplete="off"	/>
</p>
<script type="text/javascript">
function findValue(li) 
	{	
		if( li == null ) return alert("No match!");		// if coming from an AJAX call, let's use the CityId as the value
		if( !!li.extra ) var sValue = li.extra[0];		// otherwise, let's just display the value in the text box
		else var sValue = li.selectValue;				// alert("The value you selected was: " + sValue);
	}
  function selectItem(li) 	{	findValue(li);	}
  function formatItem(row)	{	return row[0];	}
  function lookupLocal()	
	{	var oSuggest = $("#Tags")[0].autocompleter;
		oSuggest.findValue();
		return false;
	}
    $("#Tags").autocomplete("recherche2.php",
		{	
			delay:10,minChars:1,	
			onItemSelect:selectItem,
			onFindValue:findValue,
			formatItem:formatItem,
			autoFill:true
		}
    );
</script>
</body>
</html>
et surtout la recherche en PHP/Mysql :
recherche2.php :
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php 
require('configuration.php');
$sql = connect_sql();
$q = strtolower($_GET["q"]);
if (!$q) return;
mysql_query("SET NAMES utf8");
$sql2 = mysql_query("SELECT nom, ville FROM lieu WHERE nom LIKE '%$q%' ");
while($rs = mysql_fetch_array($sql2)) 
{
	$res = $rs['nom'];
	echo stripslashes($res)."\n";
}
?>
fazpedro est déconnecté   Envoyer un message privé Réponse avec citation 00
Réponse Proposer ce sujet en actualité Cette discussion est résolue.
Outils de la discussion



Fuseau horaire GMT +2. Il est actuellement 20h11.


 
 
 
 
Partenaires

Hébergement Web