简体   繁体   English

Symfony2 Ajax根本不启动

[英]Symfony2 Ajax not initiating at all

I have a script that increases an arrays value by 1 everytime I click a button. 我有一个脚本,每次单击按钮时,该脚本都会将数组值增加1。 It seems like an easy task and im sure the function itself is working. 这似乎是一项简单的任务,并且确定该函数本身正在运行。 However the ajax part is not initializing at all, but the jQuery before ajax is working... Since im no expert in ajax I bet the problem is somewhere in the script. 但是,ajax部分根本没有初始化,但是ajax之前的jQuery起作用了……由于我不是ajax的专家,我敢打赌,问题出在脚本中。

So this is the simple twig: 所以这是简单的树枝:

   <tbody class="test">      

         {% if product is defined %}

              {% for info in product %}

                <tr>

                  <td> <img width="60" src="{{ asset('bundles/mpFrontend/assets/products/6.jpg') }}" alt=""/></td>

                  <td>{{ info.model }}</td>
                  <td>

                  {% for key, item in cart %}



                    <div class="input-append">

                    <input class="span1" style="max-width:34px" placeholder="{{ key }}" value="{{ item }}" id="appendedInputButtons" size="16" type="text" data-id="{{ key }}"/>
                    <button class="btn" type="button"><a href="javascript:void(0)"><i class="icon-minus"></i></a></button>
                    <a href="javascript:void(0)" class="plus btn"><i class="icon-plus"></i></a>

                    {% endfor %}

                    {% for key in cart|keys %}

                    {% if key == info.id %}

                    <button class="btn btn-danger" type="button"><a href="{{ path('cart_remove', {'id': key}) }}"><i class="icon-remove icon-white"></i></button>

                        {% endif %}
                    {% endfor %}
                    </div>

                  </td>

                  <td>{{ info.price }}</td>
                  <td>{{ info.discount }}</td>
                  <td>{{ info.value }}</td>


                  <td>{{ info.getFinal|number_format(2, '.', ',') }}</td>


                </tr>


 {% endfor %}

My script looks like this: 我的脚本如下所示:

$(document).ready(function () {
     $(".test").on('click', '.plus', function (e) {
        $this = $(this);
        alert("product id " + $this.parent('.input-append').find('input').data('id') + " Quantity " + $this.parent('.input-append').find('input').val())
        $.ajax({
            type: 'POST',
            url: /cart/update,
            async: false,
            dataType: 'JSON',
            data: {
                product: $this.parent('.input-append').find('input').data('id'),
                quantity: $this.parent('.input-append').find('input').val()
            },
            success: function (data) {
                if (data.success == false) {
                    alert('error')
                }
            }
        });
    });
});

The controller: 控制器:

/**
 * @Route("/cart/update", name="cart_update")
 */
public function cartUpdateAction( Request $request ) {
    $response = new JsonResponse();
    $requestData = $request->request->all();
    $productid     = $requestData['product'];/** first put all validations not empty/ is numeric and exists in your db etc*/
    $quantity = $requestData['quantity'];/** first put all validations not empty/ is numeric etc */
    /** if all is good then put your logic*/
    $product = $em->getRepository('MpShopBundle:Product')->find($productid);
    $qtyAvailable = $product->getStock();
    $session = $this->getRequest()->getSession();
    $cart = $session->get('cart', array());
    if ( $qtyAvailable > $cart[ $productid ] ) {
        $cart[ $productid ] = $cart[ $productid ] + 1;
        $response->setData(array('success'=>true,'message'=>'Qunatity increased'));
    } else {
        $response->setData(array('success'=>false,'message'=>'Out of stock'));
    }
    return $response;
}

Now the JQuery part is working ant the alert is showing me the id and quantity of the product. 现在,JQuery部分正在运行,并且警报正在向我显示产品的ID和数量。 But after that nothing happens. 但是之后没有任何反应。 And in the little Symfony2 toolbar at the bottom of the page, where the ajax requests should be displayed im just getting that there are no ajax requests yet.. any ideas? 并且在页面底部的小Symfony2工具栏中,应该在显示ajax请求的地方,只是得到没有ajax请求的意思。

BIG UPDATE 大更新

Looks like I fixed all of the bugs, since I am not getting any more errors in the profiler, however I am still getting the same problem. 看起来我已经解决了所有错误,因为在探查器中没有收到更多错误,但是仍然遇到相同的问题。 The Ajax is just not doing anything. Ajax只是不做任何事情。 This is what I changed: 这是我更改的内容:

I changed the url of the script and removed the async:false since Its not really needed here: 我更改了脚本的网址,并删除了async:false因为此处并不需要它:

$(document).ready(function () {
    $(document).on('click', '.plus', function (e) {
    $this = $(this);

    $.ajax({
        type: 'POST',
        url: 'update/cart',
        dataType: 'JSON',
        data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
        success: function (data) {
          if(data.success == false){
           alert('error')
          }
        }
    });
});
});

After the route change I got a new error, that the em is not defined in the update controller so I added one more line: 更改路线后,出现一个新错误,即未在更新控制器中定义em,因此我又增加了一行:

public function updateAction( Request $request ) {
    $response = new JsonResponse();
    $requestData = $request->request->all();
    $productid     = $requestData['product'];/** first put all validations not empty/ is numeric and exists in your db etc*/
    $quantity = $requestData['quantity'];/** first put all validations not empty/ is numeric etc */
    /** if all is good then put your logic*/
    $em = $this->getDoctrine()->getManager();  /// the line I added.
    $product = $em->getRepository('MpShopBundle:Product')->find($productid);
    $qtyAvailable = $product->getStock();
    $session = $this->getRequest()->getSession();
    $cart = $session->get('cart', array());
    if ( $qtyAvailable > $cart[ $productid ] ) {
        $cart[ $productid ] = $cart[ $productid ] + 1;
        $response->setData(array('success'=>true,'message'=>'Qunatity increased'));
    } else {
        $response->setData(array('success'=>false,'message'=>'Out of stock'));
    }
    return $response;
}

And I added the POST requirement in my routing(I dont know is it needed, but I saw this in other examples): 并且我在路由中添加了POST要求(我不知道是否需要它,但在其他示例中看到了这一点):

update_cart:
  pattern:  /update/cart
  defaults: { _controller: MpShopBundle:Homepage:update }
  requirements:
        _method:  POST

Now the profiler is not showing any errors, and my route is fixed(I am getting: POST http://localhost/Digidis/tree/web/app_dev.php/update/cart , and the updateAction ). 现在事件探查器未显示任何错误,并且我的路由已修复(我正在获取: POST http://localhost/Digidis/tree/web/app_dev.php/update/cart和updateAction)。 But the Ajax is still not working... I dont understand... 但是Ajax仍然无法正常工作...我不明白...

I just realised that I am not getting GET methods now, only POST.. Why is that? 我刚刚意识到我现在没有GET方法,只有POST。。为什么呢?

a59e68  ::1 POST    http://localhost/Digidis/tree/web/app_dev.php/update/cart   Wed, 06 May 2015 14:29:36 +0200
32c2e1  ::1 POST    http://localhost/Digidis/tree/web/app_dev.php/update/cart   Wed, 06 May 2015 14:29:35 +0200
6ec8ff  ::1 POST    http://localhost/Digidis/tree/web/app_dev.php/update/cart   Wed, 06 May 2015 14:29:33 +0200
4ac156  ::1 POST    http://localhost/Digidis/tree/web/app_dev.php/update/cart   Wed, 06 May 2015 14:29:32 +0200
04c5a1  ::1 POST    http://localhost/Digidis/tree/web/app_dev.php/update/cart   Wed, 06 May 2015 14:29:31 +0200
968789  ::1 POST    http://localhost/Digidis/tree/web/app_dev.php/update/cart   Wed, 06 May 2015 14:29:29 +0200
c8372b  ::1 POST    http://localhost/Digidis/tree/web/app_dev.php/update/cart   Wed, 06 May 2015 14:29:28 +0200
97192f  ::1 POST    http://localhost/Digidis/tree/web/app_dev.php/update/cart   Wed, 06 May 2015 14:29:26 +0200
dff8a3  ::1 POST    http://localhost/Digidis/tree/web/app_dev.php/update/cart   Wed, 06 May 2015 14:20:47 +0200
e4177b  ::1 POST    http://localhost/Digidis/tree/web/app_dev.php/update/cart   Wed, 06 May 2015 14:20:46 +0200

It looks like you've solved your first issue by registering the path in routing.yml, but you introduced a small issue with the update 看来您已经通过在routing.yml中注册路径解决了您的第一个问题,但是您在更新中引入了一个小问题

Based on your second update, you can see that your application is having trouble finding the path: 根据第二次更新,您可以看到您的应用程序在查找路径时遇到了麻烦:

http://localhost/Digidis/tree/web/app_dev.php/%7B%7Bpath('update_cart')%7D%7D

which url decoded, becomes: 解码的网址变为:

{{path('update_cart')}}

The solution is that your $.ajax JS line which currently reads: 解决方案是您的$ .ajax JS行当前显示为:

url: "{{path('update_cart')}}",

Should read 应该读

url: "/cart/update/",

This is because unfortunately you cannot use twig markup in JS fiels 这是因为不幸的是您不能在JS字段中使用树枝标记

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM