IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

jQuery Discussion :

Panier avec php et ajax


Sujet :

jQuery

  1. #1
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Mars 2012
    Messages
    13
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Mars 2012
    Messages : 13
    Points : 10
    Points
    10
    Par défaut Panier avec php et ajax
    bonjour à tous,

    a forcer de chercher et de ne pas trouver je viens finalement vous demander l'aider


    avec des bouts de code glané sur ce site j'essaye de faire un panier ajax
    qui envoi les information en BDD

    voici le code de la page qui traite la saisie des quantités et les ref articles

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    <script Type="text/javascript" language="JavaScript">
    $(function() {
    	$('#add').click(function(){ 		
     
    		var nam_e = $('#idarticle').val();
    		var qt_e = $('#idqte').val();
     
    		$.ajax({
       		type: "POST",
       		url: "ajout-panier.php",
       		cache: false,
       		async: false,
       		data: "refarticle=" + nam_e + "&amp;qteartic=" + qt_e ,
       		success: function(msg){   
    				$("#valeur_ajoute").fadeIn(1000).delay(2000).fadeOut(1000);             	          	             
              		$('#idqte').val('');
    			}
     		});	 		
    	}); 
    });
    </script>-->
    le tableau qui intègre les articles est dans une autre page inclue dans la première

    Code php : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    <table BORDER=1>
    <tr>
    	<td colspan=3 rowspan=6><img src="<?php echo $row['image'] ?> " WIDTH="140" height="118" alt="<?php echo $row['Article'];?>"></td>
    	<td colspan=4 width=350><center><font size=5><b><?php echo $row['Article'];?></b></font></center></td>
    	<td rowspan=6 width=350>
    		<table border=0>
    			<?php if (($row['ref'])!='AEH38DR') {
    			//<a href="javascript:ajax_panier(\'ajout-panier.php?refarticle=K'.$row['ref'].'N&qteartic=1\',panier);"><button >+</button></a>
    			//<a href="javascript:ajax_panier('panier.php?action=ajout&l=produit3&q=1&p=3','panier');"
    			echo '<tr><form method="POST" action="ajout-panier.php">
    						<td colspan=3></td>
    						<td><img src="../../img/noir.png" alt="noir"></td>
    						<td>Kit Pré-encré Noir</td>
    						<td align=right width="100px">
    						<<input type="hidden" name="refarticle" id="idarticle" value="K'.$row['ref'].'B" />
    						<input  name="qteartic" id="idqteartic" />
    													</td>
    						<td width=50px ></form>
    						<center>
    							<button class="btn primary" id="add"/>+</button><button class="btn primary" id="down"/> - </button>
    							</center>
    										</center></td>
    					</tr>
    					<tr><td colspan=7><center><div class="alert-message success" id="valeur_ajoute">Votre message a bien été envoyé</div></center></td></tr>	
    				<tr>
    						<td colspan=3><form method="POST" action="ajout-panier.php"></td>
    						<td><img src="../../img/blue.png" alt="Bleu"></td>
    						<td>Kit Pré-encré bleu</td>
    						<td align=right width="100px">
    						<input type="hidden" name="refarticle" id="idarticle" value="K'.$row['ref'].'B" />
    						<input  name="qteartic" id="idqteartic" />
    													</td>
    						<td width=50px ></form>
    						<center>
    							<button class="btn primary" id="add"/>+</button><button class="btn primary" id="down"/> - </button>
    							</center>

    enfin je tente de récupere les valeurs dans un troisieme fichier qui les envoie en BDD
    Code php : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    $numc=$_SESSION['numc'];
     
    include ('allumer.php');
     
     
     
       //récuperation des variables en POST ou GET
      if ( isset($_POST['refarticle'])) { $art=$_POST['refarticle'] } else $art="";  
      if ( isset($_POST['qteartic'])) { $qteart=$_POST['qteartic'] } else $qteart="";  
    // On commence par récupérer les champs
     
    echo "<p>recup art= ".$art;
    echo "<p>recup la qte= ".$qteart;
    if ($qteart!=""){
     
    $art=AddSlashes($art);
    $qteart=AddSlashes($qteart);


    malheureusement je n'arrive pas a traiter les articles sauf le premier

    que faire pour pouvoir traiter tous les articles de la page

  2. #2
    Rédacteur

    Avatar de danielhagnoul
    Homme Profil pro
    Étudiant perpétuel
    Inscrit en
    Février 2009
    Messages
    6 389
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 73
    Localisation : Belgique

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

    Informations forums :
    Inscription : Février 2009
    Messages : 6 389
    Points : 22 933
    Points
    22 933
    Billets dans le blog
    125

    Blog

    Sans l'analyse et la conception, la programmation est l'art d'ajouter des bogues à un fichier texte vide.
    (Louis Srygley : Without requirements or design, programming is the art of adding bugs to an empty text file.)

  3. #3
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Mars 2012
    Messages
    13
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Mars 2012
    Messages : 13
    Points : 10
    Points
    10
    Par défaut
    merci pour ta réponse danielhagnoul,

    c'est sur ce tuto que je me suis basé,
    mais je n'arrive pas à envoyer les articles au panier
    c'est peux explicite de ce coté la

  4. #4
    Rédacteur

    Avatar de danielhagnoul
    Homme Profil pro
    Étudiant perpétuel
    Inscrit en
    Février 2009
    Messages
    6 389
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 73
    Localisation : Belgique

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

    Informations forums :
    Inscription : Février 2009
    Messages : 6 389
    Points : 22 933
    Points
    22 933
    Billets dans le blog
    125
    Par défaut
    Bonsoir

    Je croyais ce tutoriel pour débutant en PHP un peu mieux fini. En regardant dans les commentaires du tutoriel, j'ai vu une méthode pour ajouter au panier. J'ai amélioré l'en-tête HTML.

    C'est tout ce que je peux faire pour vous en PHP, car je ne connais pas et ce n'est pas ma tasse de thé.

    Fichier fonctions-panier.php non modifié :
    Code php : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    <?php
     
    /**
     * Verifie si le panier existe, le créé sinon
     * @return booleen
     */
    function creationPanier(){
       if (!isset($_SESSION['panier'])){
          $_SESSION['panier']=array();
          $_SESSION['panier']['libelleProduit'] = array();
          $_SESSION['panier']['qteProduit'] = array();
          $_SESSION['panier']['prixProduit'] = array();
          $_SESSION['panier']['verrou'] = false;
       }
       return true;
    }
     
     
    /**
     * Ajoute un article dans le panier
     * @param string $libelleProduit
     * @param int $qteProduit
     * @param float $prixProduit
     * @return void
     */
    function ajouterArticle($libelleProduit,$qteProduit,$prixProduit){
     
       //Si le panier existe
       if (creationPanier() && !isVerrouille())
       {
          //Si le produit existe déjà on ajoute seulement la quantité
          $positionProduit = array_search($libelleProduit,  $_SESSION['panier']['libelleProduit']);
     
          if ($positionProduit !== false)
          {
             $_SESSION['panier']['qteProduit'][$positionProduit] += $qteProduit ;
          }
          else
          {
             //Sinon on ajoute le produit
             array_push( $_SESSION['panier']['libelleProduit'],$libelleProduit);
             array_push( $_SESSION['panier']['qteProduit'],$qteProduit);
             array_push( $_SESSION['panier']['prixProduit'],$prixProduit);
          }
       }
       else
       echo "Un problème est survenu veuillez contacter l'administrateur du site.";
    }
     
     
     
    /**
     * Modifie la quantité d'un article
     * @param $libelleProduit
     * @param $qteProduit
     * @return void
     */
    function modifierQTeArticle($libelleProduit,$qteProduit){
       //Si le panier éxiste
       if (creationPanier() && !isVerrouille())
       {
          //Si la quantité est positive on modifie sinon on supprime l'article
          if ($qteProduit > 0)
          {
             //Recharche du produit dans le panier
             $positionProduit = array_search($libelleProduit,  $_SESSION['panier']['libelleProduit']);
     
             if ($positionProduit !== false)
             {
                $_SESSION['panier']['qteProduit'][$positionProduit] = $qteProduit ;
             }
          }
          else
          supprimerArticle($libelleProduit);
       }
       else
       echo "Un problème est survenu veuillez contacter l'administrateur du site.";
    }
     
    /**
     * Supprime un article du panier
     * @param $libelleProduit
     * @return unknown_type
     */
    function supprimerArticle($libelleProduit){
       //Si le panier existe
       if (creationPanier() && !isVerrouille())
       {
          //Nous allons passer par un panier temporaire
          $tmp=array();
          $tmp['libelleProduit'] = array();
          $tmp['qteProduit'] = array();
          $tmp['prixProduit'] = array();
          $tmp['verrou'] = $_SESSION['panier']['verrou'];
     
          for($i = 0; $i < count($_SESSION['panier']['libelleProduit']); $i++)
          {
             if ($_SESSION['panier']['libelleProduit'][$i] !== $libelleProduit)
             {
                array_push( $tmp['libelleProduit'],$_SESSION['panier']['libelleProduit'][$i]);
                array_push( $tmp['qteProduit'],$_SESSION['panier']['qteProduit'][$i]);
                array_push( $tmp['prixProduit'],$_SESSION['panier']['prixProduit'][$i]);
             }
     
          }
          //On remplace le panier en session par notre panier temporaire à jour
          $_SESSION['panier'] =  $tmp;
          //On efface notre panier temporaire
          unset($tmp);
       }
       else
       echo "Un problème est survenu veuillez contacter l'administrateur du site.";
    }
     
     
    /**
     * Montant total du panier
     * @return int
     */
    function MontantGlobal(){
       $total=0;
       for($i = 0; $i < count($_SESSION['panier']['libelleProduit']); $i++)
       {
          $total += $_SESSION['panier']['qteProduit'][$i] * $_SESSION['panier']['prixProduit'][$i];
       }
       return $total;
    }
     
     
    /**
     * Fonction de suppression du panier
     * @return void
     */
    function supprimePanier(){
       unset($_SESSION['panier']);
    }
     
    /**
     * Permet de savoir si le panier est verrouillé
     * @return booleen
     */
    function isVerrouille(){
       if (isset($_SESSION['panier']) && $_SESSION['panier']['verrou'])
       return true;
       else
       return false;
    }
     
    /**
     * Compte le nombre d'articles différents dans le panier
     * @return int
     */
    function compterArticles()
    {
       if (isset($_SESSION['panier']))
       return count($_SESSION['panier']['libelleProduit']);
       else
       return 0;
     
    }
     
    ?>

    Fichier panier.php modifié :
    Code php : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    <?php
    session_start();
    include_once("fonctions-panier.php");
     
    $erreur = false;
     
    $action = (isset($_POST['action'])? $_POST['action']:  (isset($_GET['action'])? $_GET['action']:null )) ;
    if($action !== null)
    {
       if(!in_array($action,array('ajout', 'suppression', 'refresh')))
       $erreur=true;
     
       //récuperation des variables en POST ou GET
       $l = (isset($_POST['l'])? $_POST['l']:  (isset($_GET['l'])? $_GET['l']:null )) ;
       $p = (isset($_POST['p'])? $_POST['p']:  (isset($_GET['p'])? $_GET['p']:null )) ;
       $q = (isset($_POST['q'])? $_POST['q']:  (isset($_GET['q'])? $_GET['q']:null )) ;
     
       //Suppression des espaces verticaux
       $l = preg_replace('#\v#', '',$l);
       //On verifie que $p soit un float
       $p = floatval($p);
     
       //On traite $q qui peut etre un entier simple ou un tableau d'entier
     
       if (is_array($q)){
          $QteArticle = array();
          $i=0;
          foreach ($q as $contenu){
             $QteArticle[$i++] = intval($contenu);
          }
       }
       else
       $q = intval($q);
     
    }
     
    if (!$erreur){
       switch($action){
          Case "ajout":
             ajouterArticle($l,$q,$p);
             break;
     
          Case "suppression":
             supprimerArticle($l);
             break;
     
          Case "refresh" :
             for ($i = 0 ; $i < count($QteArticle) ; $i++)
             {
                modifierQTeArticle($_SESSION['panier']['libelleProduit'][$i],round($QteArticle[$i]));
             }
             break;
     
          Default:
             break;
       }
    }
     
    ?>
    <!DOCTYPE html>
    <html lang="fr" dir="ltr">
    <head>
    	<meta charset="utf-8">
    	<meta name="viewport" content="initial-scale=1.0">
    	<title>Votre panier</title>
    </head>
    <body>
    	<form method="post" action="panier.php">
    	<table style="width: 400px">
    		<tr>
    			<td colspan="4">Votre panier</td>
    		</tr>
    		<tr>
    			<td>Libellé</td>
    			<td>Quantité</td>
    			<td>Prix Unitaire</td>
    			<td>Action</td>
    		</tr>
     
     
    		<?php
    		if (creationPanier())
    		{
    		   $nbArticles=count($_SESSION['panier']['libelleProduit']);
    		   if ($nbArticles <= 0)
    		   echo "<tr><td>Votre panier est vide </ td></tr>";
    		   else
    		   {
    		      for ($i=0 ;$i < $nbArticles ; $i++)
    		      {
    		         echo "<tr>";
    		         echo "<td>".htmlspecialchars($_SESSION['panier']['libelleProduit'][$i])."</ td>";
    		         echo "<td><input type=\"text\" size=\"4\" name=\"q[]\" value=\"".htmlspecialchars($_SESSION['panier']['qteProduit'][$i])."\"/></td>";
    		         echo "<td>".htmlspecialchars($_SESSION['panier']['prixProduit'][$i])."</td>";
    		         echo "<td><a href=\"".htmlspecialchars("panier.php?action=suppression&l=".rawurlencode($_SESSION['panier']['libelleProduit'][$i]))."\">XX</a></td>";
    		         echo "</tr>";
    		      }
     
    		      echo "<tr><td colspan=\"2\"> </td>";
    		      echo "<td colspan=\"2\">";
    		      echo "Total : ".MontantGlobal();
    		      echo "</td></tr>";
     
    		      echo "<tr><td colspan=\"4\">";
    		      echo "<input type=\"submit\" value=\"Rafraichir\"/>";
    		      echo "<input type=\"hidden\" name=\"action\" value=\"refresh\"/>";
     
    		      echo "</td></tr>";
    		   }
    		}
    		?>
    	</table>
    	</form>
    	<p>&nbsp;</p>
    	<form id="form1" name="form1" method="post" action="panier.php">
    	  <p>Produit : 
    	    <input type="text" name="l" id="l" />
    	  </p>
    	  <p>Qté : 
    	    <input type="text" name="q" id="q" />
    	  </p>
    	  <p>Prix : 
    	    <input type="text" name="p" id="p" />
    	  </p>
    	  <p>
    	    <input type="submit" name="action" id="action" value="ajout" />
    	  </p>
    	</form>
    </body>
    </html>

    Blog

    Sans l'analyse et la conception, la programmation est l'art d'ajouter des bogues à un fichier texte vide.
    (Louis Srygley : Without requirements or design, programming is the art of adding bugs to an empty text file.)

  5. #5
    Membre averti Avatar de Njörd
    Homme Profil pro
    Inscrit en
    Janvier 2010
    Messages
    190
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Janvier 2010
    Messages : 190
    Points : 390
    Points
    390
    Par défaut
    Bonjour Zoulouseb,

    D'abord, il est normal que tu ne puisse traiter qu'un seul article et non plusieurs. Ton table possède deux fois un formulaire avec les mêmes ID, NAME sur tes input et bouton.

    Du coup, quand tu fais $('#add').click() il y a conflit, de même lorsque tu veux récupérer une valeur d'un champ avec $('#NomDUChamp').val().

    Ensuite, les noms de tes champs ne correspondent pas dans la fonction JS :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    var qt_e = $('#idqte').val();
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    <input  name="qteartic" id="idqteartic" />
    Sinon côté php avec l'ajout dans le panier, tu as des erreurs à nous donner ?

  6. #6
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Mars 2012
    Messages
    13
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Mars 2012
    Messages : 13
    Points : 10
    Points
    10
    Par défaut
    bonjour et merci de ton aide Njörd,

    effectivement je me doutais que le problème était à ce niveau la mis je ne vois pas comment le résoudre aurais tu ne piste ??

    aussi non du coté traitement php tout fonctionne bien

    car si je le transforme ma page article avec une simple <form> je n'ai pas de soucis

    mon seul soucis est du coté traitement avec les id

    mettre des id différents ok facile mais comment faire pour que mon script ajax / JS traite correctement les infor

    (php ok html et css aussi mais javascript un peu dur pour moi )

Discussions similaires

  1. Question sur le tutoriel panier en PHP par Joris CROZIER
    Par grinding_yanus dans le forum EDI, CMS, Outils, Scripts et API
    Réponses: 3
    Dernier message: 05/11/2015, 16h21
  2. [AJAX] panier avec ajax
    Par kate59 dans le forum AJAX
    Réponses: 1
    Dernier message: 04/06/2009, 00h27
  3. [AJAX] Introduction à AJAX et interaction avec PHP
    Par Yogui dans le forum Contribuez
    Réponses: 0
    Dernier message: 13/09/2006, 18h40
  4. [Ajax] Petit problème avec PHP et AJAX
    Par cerede2000 dans le forum Bibliothèques et frameworks
    Réponses: 9
    Dernier message: 06/05/2006, 17h58

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo