imrulhasan273
1 month ago

How can I fix the JQuery-Ajax request and response in Laravel?

Posted 1 month ago by imrulhasan273

I am trying to pass product ID to the controller through JQuery-Ajax method.

Frontend.blade.php

<script type="text/javascript">
        $(document).ready(function(){
        let x;
        <?php
             $maxP = count($products);
             for($i = 0;$i<$maxP;$i++)
             { ?>
                $('#addCart<?php echo $i; ?>').click(function() {
                    x = pro_id<?php echo $i;?> = $('#pro_id<?php echo $i;?>').val();
                    var ID = x;			//this ID contains the id of a product. 
                    $.ajax({
                        type:'get',
                        url:"{{ route('ajaxcart') }}",
                        data:{'id':ID},					
                        success:function(data){
                            alert('Data:',data); 
                        },
                        error:function(){
                        }
                    });
                });
       <?php } ?>
        });
    </script>

I sent data to the controller. But the data is not sending. when I try to fetch the data it is not collecting.

web.php

Route::get('/cart/add', '[email protected]')->name('ajaxcart')->middleware('auth');

CartController.php

public function ajax(Request $request)
{


    $data = $request->id;
    return response()->json($data);
}

Here I in $request the id is not getting. So sending data is unseccesfull

Again I try the response setting $data=10 . hence this 10 is not even getting in

Probably the php codes is the reason for that. But I need to use php as I have to make a add to cart button for different product.

Please sign in or create an account to participate in this conversation.