mardi 24 mars 2020

How to display rating stars Laravel and Ajax

I have created a review system which allows a user to add a review in a product and display the rating stars. So if a user rate a product with 4 it should display 4 full stars and one empty star(just like other review system). How can I loop and display each rating stars according to users reviews?

This is the data received from controller (console.log())

data: Array(2)
0: "4" //This is the rating for user 1
1: "3"  // This is for user 2
length: 2

Controller

 $products = Product::where('id','=',$id)->with('reviews.user')->get();
        $data = array(); 
        foreach ($products as $product)
        {
        foreach ($product->reviews as $review){
        $data []= $review->rating; 
        }
        }
        return response()->json(['code' => 200,'data' => $data]);

Ajax

  function UserRateStars() {
  $.ajax({
    type: "GET",
    url: '',
    success: function(data) {
        document.getElementById("UserRateStars").innerHTML = UserRateStars(3.6);

        function UserRateStars(rating) {

            // Round to nearest half
            rating = Math.round(data * 2) / 2;
            let output = [];
            console.log(data);
            // Append all the filled whole stars
            for (var i = rating; i >= 1; i--)
                output.push('<div >full star</div>&nbsp;');

            // If there is a half a star, append it
            if (i == .5) output.push('<div >half star</div>&nbsp;');

            // Fill the empty stars
            for (let i = (5 - rating); i >= 1; i--)
                output.push('<div>empty star</div>&nbsp;');

            return output.join('');

        }

    }
});

}
UserRateStars();


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire