user11710915
user11710915

Reputation: 434

Getting data from controller to the view Laravel with Javascript

I'm trying to get a selected product(id) from view to controller but it only shows the first product(id). So I have a loop of products which shows image of each product what I want is when a user select any image it should send the id according to the selected product. So far it only pick the first product id even if I click the last product(image) or any different image it only send the first product id. How can I fix this?

Blade

  @foreach($products as $product)
    @if(count($product->ProductsPhoto))
    <a  href="javascript:;" class="view-product" >
    <img src="{{Storage::url($product->ProductsPhoto[0]->filename)}}" alt=""  >
      </a>
   @else
        @endif
    @endforeach

Javascript

<?php  $id = $product->id; ?>
<script>
  $('.view-product').on("click", function(event) {
  $("#view-product").modal('show');
  $.ajax({
    url: '{{route('view.producT', $id)}}',
    type: 'GET',
    dataType: 'json',
  }).done(function(response) {
    console.log('received this response: '+response);
  });
});

</script>

Route

Route::get('view-product/{id}', 'HomeController@viewProduct')->name('view.producT');

Controller

public function viewProduct($id)
{
  dd($id);
}

Upvotes: 0

Views: 510

Answers (1)

Kelvin
Kelvin

Reputation: 1114

Of course you are not sending the id on each product

you are sent the id by using <?php $id = $product->id; ?> and $product was from @foreach($products as $product) @endoferach

however $id would be return the same id

you can send the product id on html and get it from javascript

@foreach($products as $product)
    @if(count($product->ProductsPhoto))
        <a class="view-product" id="{{$product->id}}">
            <img src="{{Storage::url($product->ProductsPhoto[0]->filename)}}" alt=""  >
        </a>
   @endif
@endforeach

thats how your a href by adding id="{{$product->id}}"

<script>
    $('.view-product').on("click", function(event) {
        var product_id = $(this).attr("id"); //this how you get the product_id
        var url = '{{route('view.producT',[":product_id"])}}'; // you cant combine js value on laravel route
        //then you need to replace it using below way
        url = url.replace(':product_id', product_id);
        $("#view-product").modal('show');
        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'json',
        }).done(function(response) {
            console.log('received this response: '+response);
        });
    });

</script>

Upvotes: 1

Related Questions