0

I want to get all products by category when clicked on the category name. I get data from the database but couldn't load that in view using ajax.

My controller code

public function getCategoryItems($id) {
    $category = FoodItemCategory::find($id);
    $products = $category->foods()->get();
    $data   = [];
    $image  = [];
    $prices = [];
    foreach ($products as $product) {
        foreach ($product->price as $price) {
            $data[]   = $product->name;
            $image[]  = $product->image;
            $prices[] = $price->discounted_price;

        }
    }
return response()->json(['data' => $data, 'image' => $image, 'price' => $prices]);
}

In ajax success response, I'm trying this way

success: function(response) {
   if (response) {           
      $.each(response.data, function(key, value) {
         $.each(response.image, function(key, image) {
             // console.log(response.products);
             // var href = window.location.pathname;
             var href = "{{ route('home') }}/";
             $("#category").append(
             "<div class='col-md-11 col-lg-10 col-xl-6 menu-holder left fixed'><a href='' class='menu-thumb'>
                  <img src='" + href + "storage/items/food/" + image +"' height='80' width='80'></a>" +
             "<div class='menu-item'><h5 class='color-fff'><a href=''></a> 
                   <span class='dots'>" +value +"</span>
                   <span class='price'><span> ৳ </span>21</span></h5>
                   <ul> 
                       <li>" +"<a href=''>" + value +"</a></li>
                   </ul>
              </div>
              </div>"
             );

        });
   });

here is the console.log(response) screenshot. See this image of what I get in the console

[first click] 1

2nd click

but it shows the same data twice. Can anyone tell me the right way to view this data using ajax?

Here is the dd($products)

  Illuminate\Database\Eloquent\Collection {#1252 ▼
    #items: array:2 [▼
0 => App\Models\FoodItem {#1308 ▼
  #guarded: []
  #connection: "mysql"
  #table: "food_items"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:7 [▼
    "id" => 25
    "name" => "Burger"
    "image" => "bg1.jpg"
    "is_visible" => 1
    "is_available" => 1
    "created_at" => "2021-02-07 03:19:39"
    "updated_at" => "2021-02-07 03:19:39"
  ]
  #original: array:11 [▼
    "id" => 25
    "name" => "Burger"
    "image" => "bg1.jpg"
    "is_visible" => 1
    "is_available" => 1
    "created_at" => "2021-02-07 03:19:39"
    "updated_at" => "2021-02-07 03:19:39"
    "pivot_food_item_category_id" => 44
    "pivot_food_item_id" => 25
    "pivot_created_at" => "2021-02-07 03:19:39"
    "pivot_updated_at" => "2021-02-07 03:19:39"
  ]
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:1 [▼
    "pivot" => Illuminate\Database\Eloquent\Relations\Pivot {#1098 ▼
      +incrementing: false
      #guarded: []
      #connection: "mysql"
      #table: "food_items_have_categories"
      #primaryKey: "id"
      #keyType: "int"
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:4 [▼
        "food_item_category_id" => 44
        "food_item_id" => 25
        "created_at" => "2021-02-07 03:19:39"
        "updated_at" => "2021-02-07 03:19:39"
      ]
      #original: array:4 [▶]
      #changes: []
      #casts: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      +pivotParent: App\Models\FoodItemCategory {#1163 ▶}
      #foreignKey: "food_item_category_id"
      #relatedKey: "food_item_id"
    }
  ]
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
}
1 => App\Models\FoodItem {#1059 ▶}

] }

ihprince
  • 147
  • 1
  • 2
  • 17
  • Did you check the response data from the controller? Because seems like data is duplicated from the controller response – Tharindu Feb 07 '21 at 06:27
  • from controller data is not duplicated.. see this { "data": [ "Beef burger", "Spicy Big Burger" ], "image": [ "bg4.jpg", "XRBP4RNF4RBZXISJ4SDK7GVOWY.jpg" ], "price": [ 165, 262 ] } – ihprince Feb 07 '21 at 06:31
  • please ``console.log(response)`` and add to your code – Zia Yamin Feb 07 '21 at 06:34
  • Added & I get this : {data: Array(2), image: Array(2), price: Array(2)} data: (2) ["Beef burger", "Spicy Big Burger"] image: (2) ["bg4.jpg", "XRBP4RNF4RBZXISJ4SDK7GVOWY.jpg"] price: (2) [165, 262] __proto__: Object – ihprince Feb 07 '21 at 06:40
  • why you used the ``jquery`` loop twice after the ``success`` function in your ajax? – Zia Yamin Feb 07 '21 at 06:48
  • I don't know, I stucked here more than 4hour, My brain is not working. Can you explain what to do? – ihprince Feb 07 '21 at 06:55
  • please ``dd($products )`` in your controller and show the result, then I will give your answer. – Zia Yamin Feb 07 '21 at 07:09
  • I edited the post, please check it – ihprince Feb 07 '21 at 07:15
  • can you tell me how to clear div before append?? I try this $("#category").empty(); but it doesn't work properly – ihprince Feb 07 '21 at 07:22
  • take a look here https://stackoverflow.com/questions/13020258/reading-nested-json-via-ajax-with-jquery-or-javascript-and-outputting-to-tables – Zia Yamin Feb 07 '21 at 07:28

0 Answers0