Dominykas55
Dominykas55

Reputation: 1231

Symfony2 Ajax not initiating at all

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.

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?

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:

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

$(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:

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):

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...

I just realised that I am not getting GET methods now, only POST.. Why is that?

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

Upvotes: 0

Views: 168

Answers (1)

Anuj
Anuj

Reputation: 1474

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

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:

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

Should read

url: "/cart/update/",

This is because unfortunately you cannot use twig markup in JS fiels

Upvotes: 1

Related Questions