Symfony2 Ajax根本没有启动

时间:2022-10-25 16:47:36

I have a script that increases an arrays value by 1 everytime I click a button. 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.

我有一个脚本,每次单击按钮时,数组值都会增加1。这似乎是一项简单的任务,并确保功能本身正常工作。然而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. 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?

现在,JQuery部分正在工作,警报向我显示产品的ID和数量。但之后没有任何反应。在页面底部的小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. This is what I changed:

看起来我修复了所有错误,因为我在分析器中没有再收到任何错误,但是我仍然遇到同样的问题。 Ajax没有做任何事情。这是我改变的:

I changed the url of the script and removed the async:false since Its not really needed here:

我更改了脚本的url并删除了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 ). But the Ajax is still not working... I dont understand...

现在,探查器没有显示任何错误,我的路由已修复(我得到:POST http://localhost/Digidis/tree/web/app_dev.php/update/cart和updateAction)。但是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

1 个解决方案

#1


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:

哪个url解码,变成:

{{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 fiels中使用twig标记

#1


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:

哪个url解码,变成:

{{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 fiels中使用twig标记