2016-04-12 19 views
-1

ajaxを使用してデータベースを更新する際に問題があります。基本的に私はjQueryナンバースピナーを持っています。そのユーザーがその製品の番号をクリックすると、データベースにアップロードされます。代わりに、すべての製品がその番号に更新されるか、最後のものが更新されます。ユーザーが変更している製品だけをデータベースで変更できるようにするにはどうすればよいですか?ajax/jQueryを使用したデータベースへの更新

それは、私はjQueryの/ AJAXでの総noobのだが、私は学ぶことをしようとしていることは注目に値します。

小枝/ HTML:

{% extends '::base.html.twig' %} 

{% block body %} 

<h1 class="text-center"><u><i>Your Cart</i></u></h1> 

    <div class="container"> 

     <div class="who_is_logged_in"> 
      {% if user is null %} 
       <a href="{{ path ('fos_user_security_login') }}">Login</a> 
      {% else %} 
       <u>Hello<strong> {{ user }}</strong></u> 
      {% endif %} 
     </div> 

     <table class="table table-striped"> 
      <thead> 
       <tr> 
        <th>Product</th> 
        <th>Quantity</th> 
        <th>Price Per Unit</th>  
        <th>Remove Product</th> 
       </tr> 
      </thead> 

      <tbody> 
      {% for key, product in quantity %} 
        <tr> 
         <td>{{ product.product }}</td> <!--Product--> 
         <td> 
          <input class="spinner" value="{{ product.quantity }}" style="width:30px"> 
         </td> <!--Quantity--> 
         <td>${{ product.product.price|default('') }}</td> <!--Price--> 
         <td> 
          <a href="{{ path('product_remove', {'id': product.product.id }) }}"> 
           <button name="REMOVE" type="button" class="btn btn-danger" id="removeButton"> 
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span> 
           </button> 
          </a> 
         </td><!--Remove--> 
        </tr> 
       {% endfor %}  
      </tbody> 
     </table> <!--top table--> 

      <div class="money-container"> 
       <p class="text-right">Total Cost: ${{ totalCostOfAllProducts }}</p> 
      </div> <!--moneyContainer--> 

     {% for flash_message in app.session.flashbag.get('notice') %} 
      <div class="flash-notice"> 
       <strong>{{ flash_message }}</strong> 
      </div> <!--flashNotice--> 
     {% endfor %} 

    </div> <!--container--> 

    <ul> 
     <li> 
      <a href="{{ path('product') }}"> 
       Add More Products 
      </a> 
     </li> 
     <li> 
      <a href="{{ path('product_bought') }}"> 
       Buy These Products 
      </a> 
     </li> 
    </ul> 


    <script type="text/javascript"> 
    $(".spinner").spinner(); 
     $('input.spinner').on('spinstop', function(){ 
      min: 0 
      console.log('spinner changed'); 
      var $this = $(this); 
      var value = $('.spinner').val(); 
      var request = $.ajax({ 
       url: "{{ path('product_quantityUpdate') }}", 
       method: "POST", 
       data : { 
        quantity: this.value, 
       } 
      }).done(function(result){ 
       console.log('success', result); 
      }).error(function (xhr, ajaxOptions, thrownError) { 
       console.log(xhr.status); 
       console.log(xhr.responseText); 
       console.log(thrownError); 
      }); 
     }); 
    </script> 

{% endblock %} 

のrelaventコントローラー機能:。

/** 
* Updates quantity using ajax/jQuery request from showCart twig file 
* 
* @Route("/quantityUpdate", name="product_quantityUpdate") 
* @Method("POST") 
* @Template() 
*/ 
public function quantityUpdateAction(Request $request) { 

    $em = $this->getDoctrine()->getManager(); 

    $cart = $em->getRepository('ShopBundle:UserCart')->findOneBy(['user' => $this->getUser(), 'submitted' => false]); 

    $productsInUsersCart = $cart->getQuantities(); 

    foreach ($productsInUsersCart as $key => $value) { 

     $productsInUsersCart = $value->getQuantity(); // Within the loop, gets the quantity of the product being changed 
      $value->getProduct()->getId();  //SHOULD be the product ID 
      $value->getUserCart()->getId(); //SHOULD be the user's cart ID 

/* ----------------------------- Like Below & Will Update EVERYTHING in Users Cart ----------------------------- */ 

    // dump($request->get('id_value')); 
    // dump($request->get('prodId')); die; 
     $value->setQuantity($_POST['quantity']); 
     $em->persist($value); 
     $em->flush(); 
    } 

/* ----------------------------- Like Below & Will Update the LAST product in Users Cart ----------------------------- */ 

     // $value->setQuantity($_POST['quantity']); 
     // $em->persist($value); 
     // $em->flush(); 

    return new Response ("This has been successful!"); 
} 
+0

実際のHTML出力がない場合は、アクションを現在の行に関連付ける必要がありますが、アクションを関連付ける方法はわかりませんが、 iquely各行を識別し、 –

+0

は、私はこれを考え出したが、それは私が苦しんでんですよ。編集に自分のHTMLを追加します。行が私のアヤックスで取り出す方法を知らないidなので、私は苦労します。あなたの助けのための – Ale

答えて

0

VAR ID_VALUE = $(この).val()ID;あなたのようにそれを書くために必要なIDにアクセスするには

//パラメータなしのval()は、入力要素の値を返します

VAR ID_VALUE = $(これは).ATTR( 'ID'); //これが返されますこのはそれが$(selector).attr('id');または012を使用してアクセスするために、その後data-name=""id=""
を追加してinput.spinnerにプロダクトIDを追加し、現在の要素に

+0

おかげで再び、しかし、これは動作しません。私はあなたがそれは大丈夫ですが、私は代わりに、回避策を見つける問題を解決すると言うでしょう、問題を解決した場合はHTML – Ale

+0

を表示するように編集をした:) –

0

を指すために使用されます。要素

ノートからのid属性値をその後、

<input class="spinner" data-pid="{{product.product.id}}" value="{{product.quantity}}" style="width:30px"> 

これは1つだけ取得する、あなたはループを必要としないので、この場合には、既存の行を更新している、あなたのPHPスクリプトに数量とidを送信します

$('input.spinner').on('spinstop', function(){ 
    min: 0 
    console.log('spinner changed'); 

    var value = $(this).val(); 
    var productId = $(this).data('pid'); 

    var request = $.ajax({ 
      url: "{{ path('product_quantityUpdate') }}", 
      method: "POST", 
      data : { 
       quantity: value, 
       id: productId 
      } 
     }).done(function(result){ 
      console.log('success', result); 
     }).error(function (xhr, ajaxOptions, thrownError) { 
      console.log(xhr.status); 
      console.log(xhr.responseText); 
      console.log(thrownError); 
     }); 
} 

あなたの関数を更新行を変更してDBに格納する

$em = $this->getDoctrine()->getManager(); 
$cart = $em->getRepository('ShopBundle:UserCart')->findOneBy(['user' => $this->getUser(), 'id' => $request->request->get('id'), 'submitted' => false]); 
$cart->setQuantity($request->request->get('quantity')); 
$em->persist($cart); 
$em->flush(); 
関連する問題