【问题标题】:How to update database with jQuery/ajax?如何使用 jQuery/ajax 更新数据库?
【发布时间】:2016-04-08 16:16:28
【问题描述】:

我是 jQuery/ajax 甚至 PHP/Symfony2 的新手,但我正在学习。

我只是想使用这个 jQuery 数字微调器更新我的数据库中 Quantity 表中的 quantity 字段。

脚本确实有效(我在控制台中获得了成功),但如果我刷新页面,数量会变回默认/原始“1”。如果用户更改通过数据库更新的数量,我该如何做到这一点。我不知道如何正确地做到这一点。我需要在控制器中添加额外代码吗?

树枝:

{% 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();
        $.ajax({
            url: "{{ path('product_showCart') }}",
            method: 'POST',
            data : {
                quantity: $this.val()
            }
        }).done(function(resp){
            console.log('success', resp);
        }).error(function(err){
            console.log('error', resp);
        });
    });
</script>


{% endblock %}

ProductController相关函数:

/** 
 * Creates the option to 'add product to cart'.
 *
 * @Route("/{id}/addToCart", name="product_addToCart")
 * @Method("GET")
 * @Template()
 */
public function addToCartAction(Request $request, $id) {

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

    $product = $em->getRepository('ShopBundle:Product')->find($id);
        $product->getId();
        $product->getName();
        $product->getPrice();
    $cart = $em->getRepository('ShopBundle:UserCart')->findOneBy(['user' => $this->getUser(), 'submitted' => false]);
    // $quantity = $em->getRepository('ShopBundle:Quantity')->findOneBy(['id' => $this->getUser()]);

    if ($this->checkUserLogin()) {
        $this->addFlash('notice', 'Login to Create a Cart');
        return $this->redirectToRoute('product');
    }

    // --------------------- assign added products to userCart id ------------------------ //

    $quantity = new Quantity();

    if (is_null($cart) || $cart->getSubmitted(true)) {
        $cart = new UserCart();
    }

    $cart->setTimestamp(new \DateTime()); // Set Time Product was Added 
    $quantity->setQuantity(1);   // Set Quantity Purchased.......Make jQuery # Spinner the input of setQuantity()
    $cart->setSubmitted(false); // Set Submitted
    $cart->setUser($this->getUser());  // Sets the User ONCE
    $cart->addQuantity($quantity);    //  Add Quantity ONCE
    $quantity->setUserCart($cart);   //   Create a UserCart ONCE
    $quantity->setProduct($product); // Sets the Product to Quantity Association ONCE
    $em->persist($product);
    $em->persist($cart);
    $em->persist($quantity); 
    $em->flush();
    $this->addFlash('notice', 'The product: '.$product->getName().' has been added to the cart!');


return $this->redirectToRoute('product');

}

/**
 * Shows Empty Cart
 * 
 * @Route("/showCart", name="product_showCart")
 * @METHOD("GET")
 * @Template()
 */
public function showCartAction(Request $request) {

// --------------------------- show only what the user added to their cart --------------------------- //

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

    if ($this->checkUserLogin()) {
        $this->addFlash('notice', 'Login to Create a Cart');
        return $this->redirectToRoute('product');
    }

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

    $prodsInCartCost = $cart->getQuantities();
//BELOW just to show what I think I should do...doesn't work though
    foreach ($prodsInCartCost as $key => $value) {
        $prodsInCartCost = $value->getQuantity();
                    //Is the below condition on the right track??
        if ($request->getMethod() == 'POST') {
            $value->setQuantity([/*WHAT GOES HERE?*/]);
            $em->persist($value);
            $em->flush();
        }
    }
//end showing what I think I should do example

    if (!$cart) {
        $this->addFlash('notice', 'There is NO CART');
        return $this->redirectToRoute('product');
    }

    $sub = $cart->getSubmitted();

    /**
     * Function in UserCart that Maps to Quantity where product values lives.
     *       $quantity is an object (ArrayCollection / PersistentCollection)
     */
    if ($sub == false) {
        $quantity = $cart->getQuantities();
    } else {
        $this->addFlash('notice', 'Cart should be EMPTY');
    }

    if (!$cart) {
        throw $this->createNotFoundException(
            'ERROR: You got past Gondor with an EMPTY CART'
        );
    }

    $totalCostOfAllProducts = 0;

    $totalCostOfAllProducts = $this->getTotalCost($cart, $totalCostOfAllProducts);

    if (empty($price) && empty($quantity) && empty($totalCostOfAllProducts)) {
        $price = 0; $quantity = 0; $totalCostOfAllProducts = 0;
    }

    return array(
        'user' => $cart->getUser(),         // for :UserCart
        'cart' => $cart,
        'quantity' => $cart->getQuantities(),         // for :UserCart
        // 'quantity' => $quantity,         // for :UserCart
        'totalCostOfAllProducts'    => $totalCostOfAllProducts,
    );
}

【问题讨论】:

    标签: php jquery ajax symfony


    【解决方案1】:

    据我所知,您不能将 Flash 消息与 ajax 请求混合使用。您必须更改控制器操作以返回将在 javascript 中处理的 json 消息,并且它们可能会更改某些元素的 html 值。通过这种方式,您可以通知用户该操作成功。刷新页面后,应该以与第一次相同的方式从数据库中加载数量值。

    //controller action
        public function ajaxAction($id)
        {
           ...
           $result = array("responseCode" => 200, "data" => $data);
           return new Response(json_encode($result ), 200, array('Content-Type' => 'application/json'));
        }
    
    //js code
    $.ajax({
        url: "{{ path('product_showCart') }}",
                method: 'POST',
                data : {
                    quantity: $this.val()
                }
            }).done(function(resp){
                if (resp.responseCode == 200) {
                   $('#div_quantity').html(resp.data)
                }
            }).error(function(err){
                console.log('error', resp);
            });
    

    此代码未经测试,但您可以理解。

    【讨论】:

      猜你喜欢
      • 2016-08-03
      • 1970-01-01
      • 2015-03-22
      • 2019-08-04
      • 2011-07-10
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 2013-07-20
      相关资源
      最近更新 更多