tessguefen
10/9/2014 - 3:59 PM

Yotpo Ratings to Custom Field (Edited from Steven's)

Yotpo Ratings to Custom Field (Edited from Steven's)

// -- Save Yotpo Reviews to Custom Field -- //
        $(window).load(function(){
            var debug = false,
                rating,
                count,
                productCode = $('#product-code').text(),
                timesChecked = 0,
                storedRating = $('[itemprop="average"]').text(),
                storedCount = $('[itemprop="votes"]').text();

            function checkForRating(){
                rating = parseFloat(0);
                $('.yotpo .yoTop:first #yotpo_state_line .yoStars img').each(function( index ) {
                    if ($(this).hasClass('yoStarFull')) {
                       rating++;
                    } else if ($(this).hasClass('yoStarHalf')) {
                        rating += 0.5;
                    }
                });
                
                count = $('.yotpo .yoTop:first #yotpo_state_line .yoResultReviews').text();

                if(rating !== ''){
                    validateRating();
                } else if (timesChecked < 100) {
                    //if (debug) console.log('checked'+$('.pr-snippet-rating-decimal').text()+'-'+$('.pr-snippet-link span').text());
                    timesChecked += 1;
                    setTimeout(function(){checkForRating()},250);
                }
            }
            checkForRating();

            function validateRating(){
                if(rating !== '0.0'){
                    if(storedRating !== rating || storedCount !== count){
                        saveRating();
                    }
                }
            }

            function saveRating(){
                // ajax call to page that will save the rating and count
                $.ajax({
                    url: '/mm5/merchant.mvc',
                    type: 'POST',
                    cache: false,
                    data: {
                        Screen: 'PROD',
                        yotpoReviewRating: rating,
                        yotpoReviewsCount: count,
                        updateproductCode: productCode
                    }
                });
            }
        });