Help finding the purchase calculation

(I couldn’t find where to edit my related posting, so I’ve created this one - hope that’s not a problem)

I am using a php web video script which allows Users to purchase videos successfully. Upon selecting videos to purchase, a message shows “Simply Proceed to purchase’ , generated by the code below.

I’d like to get help to try to determine where the total price of purchasing the X (amount) of videos calculates, prior to Proceeding. The code in regard to purchasing begins about halfway at line 247:

$(".video-player").hover(
    function(e){
      $('.watermark').css('display', 'block');
     }, 
    function(e){
      setTimeout(function () {
        if ($('.video-player:hover').length == 0) {
          $('.watermark').css('display', 'none');
        }
      }, 1000);
     } 
);

$(function () {
  $.fn.scrollTo = function (speed) {
      if (typeof(speed) === 'undefined')
          speed = 500;

      $('html, body').animate({
          scrollTop: ($(this).offset().top - 100)
      }, speed);
      
      return $(this);
  };

  $('.cover-container, .edit-cover-container').hover(function() { 
      $('.edit-cover-container').removeClass('hidden'); 
  });
  $('.cover-container, .edit-cover-container').mouseleave(function() {                  
     $('.edit-cover-container').addClass('hidden'); 
  });
  
  $('.avatar-container, .edit-avatar-container').hover(function() { 
      $('.edit-avatar-container').removeClass('hidden'); 
  });
  $('.avatar-container, .edit-avatar-container').mouseleave(function() {                  
     $('.edit-avatar-container').addClass('hidden'); 
  });
  
  $('[data-toggle="tooltip"]').tooltip(); 

  $('.player-video').hover(function() { 
      $('.icons').removeClass('hidden'); 
  });
  $('.player-video').mouseleave(function() {                  
     $('.icons').addClass('hidden'); 
  });

  $
  var hash = $('.main_session').val();
  $.ajaxSetup({ 
    data: {
        hash: hash
    },
    cache: false 
  });
  if ($(window).width() < 720) {
    $('ul li').click(function(e) {
       e.stopPropagation(); 
    }); 
    $('.video-info-element').removeClass('pull-right');
  } else {
    if (!$('.video-info-element').hasClass('pull-right')) {
      $('.video-info-element').addClass('pull-right');
    }
  }
});
 
 if ($(window).width() < 720) {
    $('ul li').click(function(e) {
     e.stopPropagation(); 
   }); 

 }

function scrollToTop() {
	  verticalOffset = typeof (verticalOffset) != 'undefined' ? verticalOffset : 0;
	  element = $('html');
	  offset = element.offset();
	  offsetTop = offset.top;
	  $('html, body').animate({
	    scrollTop: offsetTop
	  }, 300, 'linear');
}
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('.thumbnail-preview img').attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
}
function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).attr("link")).selectment.execCommand("copy");
  $temp.remove();
  notif({
    msg: "Link copyed to clipboard",
    type: "default",
    fade:0,
    timeout:1500
  });
}
function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function Wo_LikeSystem(id, type, this_, is_ajax, repeat) {
   if (!id || !type) {
      return false;
   }
   if (!$('#main-container').attr('data-logged') && $('#main-url').val()) {
   	  window.location.href = PT_Ajax_Requests_File() + 'login?to=' + $('#main-url').val();
        return false;
   }
   var result = 0;
   
   if (type == 'like') {
      var likes = $(this_).attr('data-likes');
      if ($(this_).attr('liked')) {
         result = Number(likes) - 1;
         $(this_).removeAttr('liked');
         $(this_).removeClass('active');
      } else {
         result = Number(likes) + 1;
         $(this_).attr('liked', true);
         $(this_).addClass('active');
      }
      $('#likes').text(numberWithCommas(result));
      $(this_).attr('data-likes', result);
      if ($('#dislikes-bar').attr('data-likes') > 0) {
         if ($('#dislikes-bar').hasClass('active')) {
             $('#dislikes-bar').removeAttr('disliked');
             $('#dislikes-bar').removeClass('active');
             result = Number($('#dislikes-bar').attr('data-likes')) - 1;
             $('#dislikes').text(numberWithCommas(result));
             $('#dislikes-bar').attr('data-likes', result);
         }
      }
   } else if (type == 'dislike') {
      var dislikes = $(this_).attr('data-likes');
      if ($(this_).attr('disliked')) {
         result = Number(dislikes) - 1;
         $(this_).removeAttr('disliked');
         $(this_).removeClass('active');
      } else {
         result = Number(dislikes) + 1;
         $(this_).attr('disliked', true);
         $(this_).addClass('active');
      }
      $(this_).attr('data-likes', result);
      $('#dislikes').text(numberWithCommas(result));
      if ($('#likes-bar').attr('data-likes') > 0) {
         if ($('#likes-bar').hasClass('active')) {
             $('#likes-bar').removeAttr('liked');
             $('#likes-bar').removeClass('active');
             result = Number($('#likes-bar').attr('data-likes')) - 1;
             $('#likes').text(numberWithCommas(result));
             $('#likes-bar').attr('data-likes', result);
         }
      }
   }
   if (is_ajax == 'is_ajax') {
      $.post(PT_Ajax_Requests_File() + 'aj/like-system/' + type, {id: id, type:type});
   }
}

function PT_AddLike(id, this_, type , is_ajax) {
   if (!id || !type) { return false; }

   if (!$('#main-container').attr('data-logged') && $('#main-url').val()) {
        window.location.href = PT_Ajax_Requests_File() + 'login?to=' + $('#main-url').val();
        return false;
   }
    var result = 0;
    var main_comment = $('#comment-' + id);
   if (type == 'like') {
      var likes = $(this_).attr('data-likes');
      if ($(this_).attr('liked')) {
         result = Number(likes) - 1;
         $(this_).removeAttr('liked');
         $(this_).removeClass('active');
      } else {
         result = Number(likes) + 1;
         $(this_).attr('liked', true);
         $(this_).addClass('active');
      }
      main_comment.find('#comment-likes').text(numberWithCommas(result  $(this_).attr('data-likes', result);
   }
   if (type == 'dislike') {
      var likes = $(this_).attr('data-likes');
      if ($(this_).attr('liked')) {
         result = Number(likes) - 1;
         $(this_).removeAttr('liked');
         $(this_).removeClass('active');
      } 

      else {
         result = Number(likes) + 1;
         $(this_).attr('liked', true);
         $(this_).addClass('active');
      }
      main_comment.find('#comment-likes').text(numberWithCommas(result  $(this_).attr('data-likes', result);
   } 
   if (is_ajax == 'is_ajax') {
      $.post(PT_Ajax_Requests_File() + 'aj/comment-like-system/' + type, {id: id, type:type});
   }
}

var PT_Delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

function PT_progressIconLoader(container_elem) {
  container_elem.each(function() {
    progress_icon_elem = $(this).find('i.progress-icon');
    default_icon = progress_icon_elem.attr('data-icon    hide_back = false;
    if (progress_icon_elem.hasClass('hidde') == true) {
      hide_back = true;
    }
    if ($(this).find('i.fa-spinner').length == 1) {
      progress_icon_elem.removeClass('fa-spinner').removeClass('fa-spin').addClass('fa-' + default_icon);
      if (hide_back == true) {
        progress_icon_elem.hide();
      }
    } else {
      progress_icon_elem.removeClass('fa-' + default_icon).addClass('fa-spinner fa-spin').show();
    }
    return true;
  });
}

function PT_HasExtension(id, exts) {
    var fileName = $(id).val();
    return (new RegExp('(' + exts.join('|').replace(/\./g + ')
```)).test(fileName);
}

**function PT_MultipleBuyVideo() {**
    var checked = getSelectedVideos();
    if (!checked) { return false; }

    swal({
        title: "",
        type: "info",
        html:"Simply proceed to purchase " + countSelectedVideos() + " videos",
        showCancelButton: true,
        cancelButtonText: "Close",
        customClass: 'sweetalert-lg',
        confirmButtonText:'Proceed'
    }).then(function(){

        $.ajax({
            url: PT_Ajax_Requests_File() + 'aj/buy-video',
            type: 'POST',
            dataType: 'json',
            data: {id:checked},
        }).done(function(data){
            if (data.status == 200) {
                for (var i = 0; i < checked.length; i++) {
                    var button = $("button[data-action='multiple_select_button'][data-id='" + checked[i] + "']")
                    buttonMultipleSelectingStyle(button, 'purchased');
                }

                swal({
                    title: "Success",
                    type: "success",
                    html:"",
                    showCancelButton: true,
                    cancelButtonText: "Close",
                    customClass: 'sweetalert-lg',
                    confirmButtonText:'Go To Video(s)'
                }).then(function(){
                    window.location.href='/paid-list               });

            } else {
                if (data.error_num == 1) {
                    swal(
                        'Error!',
                        'Not enough money',
                        'error'
                    );
                } else {
                    swal(
                        'Error!',
                        'Something went wrong. Please try again later!',
                        'error'
                    );
                }
            }
        }).fail(function() {
            swal(
                'Error!',
                'Something went wrong. Please try again later!',
                'error'
            );
        })
    });
}

function buttonMultipleBuy(command) {
    var button = $("button[data-action='multuple-buy-video']");
    if (command == 'hide') {
        button.hide();
    } else if (command == 'show') {
        button.show();
    }
}

buttonMultipleBuy('hide');

$(document).on('click touchstart', "button[data-action='multiple_select_button']", function(){
    if ($(this).attr('data-selected') == 1) {
        // uncheck
        buttonMultipleSelectingStyle($(this), 'uncheck');
    } else {
        // check
        buttonMultipleSelectingStyle($(this), 'check');
    }

    if (countSelectedVideos()) {
        buttonMultipleBuy('show');
    } else {
        buttonMultipleBuy('hide');
    }
});

function countSelectedVideos() {
    var checked = 0;
    $("button[data-action='multiple_select_button']").each(function(i){
        if ($(this).attr('data-selected') == 1) {
            checked++;
        }
    });
    return checked;
}

function getSelectedVideos() {
    var checked = [];
    $("button[data-action='multiple_select_button']").each(function(i){
        if ($(this).attr('data-selected') == 1) {
            checked.push($(this).attr('data-id
        }
    });
    return checked;
}

function buttonMultipleSelectingStyle(button, action) {
    if (action == 'check') {
        button.attr('data-selected);
        button.css('backgroundColor#FF4500');
        button.html('Selected    } else if (action == 'uncheck') {
        button.attr('data-selected);
        button.css('backgroundColor#04abf2');
        button.html('View    } else if (action == 'purchased') {
        button.attr('data-selected);
        button.css('backgroundColor#04abf2');
        button.html('Purchased        button.attr('disableddisabled');
    }
}

function PT_ModalPlayerForPurchasedVideo(video_id, title) {
    if (!video_id) {
        return false;
    }

    $.ajax({
        url: PT_Ajax_Requests_File() + 'aj/get-modal-player',
        type: 'POST',
        dataType: 'json',
        data: {id:video_id},
    }).done(function(data) {
        if (data.status == 200) {
            swal({
                title: title,
                type: "",
                html: data.html,
                showConfirmButton: false,
                showCancelButton: true,
                cancelButtonText: "Close",
            });
        } else {
            swal(
                'Error!',
                'Something went wrong. Please try again later!',
                'error'
            );
        }
    }).fail(function() {
        swal(
            'Error!',
            'Something went wrong.Please try again later!',
            'error'
        );
    })
}



function pt_elexists(el){
  return ($(el).length > 0);
}


function nl2br (str, is_xhtml) {   
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';    
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}

function makeid() {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < 10; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

function escapeHTML(string) {
    var pre = document.createElement('pre');
    var text = document.createTextNode( string );
    pre.appendChild(text);
    return pre.innerHTML;
}

var lastScrollTop = 0;
$('.user-messages').scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       $('#load-more-messages').css('display', 'none');
   } else {
       $('#load-more-messages').css('display', 'block');
   }
   lastScrollTop = st;
});

Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
    get: function(){
        return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
    }
})




/*!
 * Snackbar v0.1.8
 * http://polonel.com/Snackbar
 *
 * Copyright 2017 Chris Brame and other contributors
 * Released under the MIT license
 * https://github.com/polonel/Snackbar/blob/master/LICENSE
 */
!function(a,b){"use strict";"function"==typeof define&&define.amd?define([],function(){return a.Snackbar=b()}):"object"==typeof module&&module.exports?module.exports=a.Snackbar=b():a.Snackbar=b()}(this,function(){var a={};a.current=null;var b={text:"Default Text",textColor:"#FFFFFF",width:"auto",showAction:!0,actionText:"X",actionTextColor:"#4CAF50",showSecondButton:!1,secondButtonText:"",secondButtonTextColor:"#4CAF50",backgroundColor:"#323232",pos:"bottom-left",duration:5e3,customClass:"",onActionClick:function(a){a.style.opacity=0},onSecondButtonClick:function(a){}};a.show=function(d){var e=c(!0,b,d);a.current&&(a.current.style.opacity=0,setTimeout(function(){var a=this.parentElement;a&&
a.removeChild(this)}.bind(a.current),500)),a.snackbar=document.createElement("div"),a.snackbar.className="snackbar-container "+e.customClass,a.snackbar.style.width=e.width;var f=document.createElement("p");if(f.style.margin=0,f.style.padding=0,f.style.color=e.textColor,f.style.fontSize="14px",f.style.fontWeight=300,f.style.lineHeight="1em",f.innerHTML=e.text,a.snackbar.appendChild(f),a.snackbar.style.background=e.backgroundColor,e.showSecondButton){varement("button");g.className="action",g.innerHTML=e.secondButtonText,g.style.color=e.secondButtonTextColor,g.addEventListener("click",function(){e.onSecondButtonClick(a.snackbar)}),a.snackbar.appendChild(g)}if(e.showAction){vart.createElement("button");h.className="action",h.innerHTML=e.actionText,h.style.color=e.actionTextColor,h.addEventListener("click",function(){e.onActionClick(a.snackbar)}),a.snackbar.appendChild(h)}e.duration&&setTimeout(function(){a.current===this&&(a.current.style.opacity=0)}.bind(a.snackbar),e.duration),a.snackbar.addEventListener("transitionend",function(b,c){"opacity"===b.propertyName&&"0"===this.style.opacity&&(this.parentElement.removeChild(this),a.current===this&&(a.current=null))}.bind(a.snackbar)),a.current=a.snackbar,"top-left"!==e.pos&&"top-center"!==e.pos&&"top"!==e.pos&&"top-right"!==e.pos||(a.snackbar.style.top="-100px"),document.body.appendChild(a.snackbar);getComputedStyle(a.snackbar).bottom,getComputedStyle(a.snackbar).top;a.snackbar.style.opacity=1,a.snackbar.className="snackbar-containera.snackbar.styla.snackbar.style.top=0:"top-center"===e.pos||"top"===e.pos?a.snackbar.style.top="25px":"bottom-center"!==e.pos&&"bottom"!==e.pos||(a.snackbar.style.bottom="-25px")},a.close=function(){a.current&&(a.current.style.opacity=0object Boolean]"===Object.prototype.toString.call(arguments[0])&&(b=arguments[0],c++);for(var e=function(c){for(var d in c)Object.prototype.hasOwnProperty.call(c,d)&&(b&&"[object Object]"===Object.prototype.toString.call(c[d])?a[d]=extend(!0,a[d],c[d]):a[d]=c[d])};c<d;c++){var f=arguments[c];e(f)}return a};return a});
//# sourceMappingURL=snackbar.min.js.map

any help will be welcomed

Hi @ChrisjChrisj, you’ll get better help if you don’t paste your entire code base but just provide the smallest amount of code necessary to reproduce the problem – check out the forum posting basics, especially the part about SSCCEs. For example, stuff like smooth scrolling certainly isn’t necessary to get the total price. And if there is backend data involved, provide appropriate mock data, e.g. using jQuery mockjax. Isolating the problem like this may already help you find a solution. :-)

BTW from a quick look at your code there also seem to be a couple of problems with the formatting as there are markdown artifacts such as backticks and asterisks.

1 Like

Further to Megapop’s point, code blocks on the forum don’t include line numbers, making the need for a SSCCE more important.

As far as

There are two answers to this:

1. It’s not actually done.

Nowhere in the current code does it appear that the price total is actually calculated. The page does appear to count the number of videos selected (there’s a function called countSelectedVideos, specifically for that purpose).

2. It would seem to be in a different file.

The purchasing process is done by handing a series of id values to a different page: aj/buy-video. It would presumably be there that the prices are calculated and totaled. As far as I can see with a very quick scan of the code here, price is never used or displayed?

(Also as Megapop said, there seems to be several missing apostrophes in your code. Uncertain if this is a copy error or a genuine problem.)

I’ve seen a few of your posts and it sounds to me like you are working on a rather large application/script and trying to change/re-engineer a fundamental component of the original system. To do that successfully requires understanding the consequences of those changes and how they might propagate throughout the rest of the code. I’m going to assume no automated testing of any kind exists for this project. Inline with that assumption it appears you are walking a very dangerous path. One can only hope this isn’t being done directly on production. Search and replace/modify on keywords isn’t a very adequate method of changing major functions of any platform like pricing.

Thanks for your replies.

I am trying to start with adding a function, but don’t know much javascript.
this is what I have so far, any additional guidance will be appreciated. For example, a suggestion for price1 + price 2.

function countTotalCredits() {
var total = price1 + price2;
$("button[data-action='multiple_select_button][data-selected=1]").closest(".video-wrapper").each(function(i){
       parseInt($(this).attr('data-price'), 10);
        }
    });
}

You’ve already got a function that collects the ID’s of the items (getSelectedVideos). Mimic it, but instead of returning the ID, add the price, and then sum the array.

Might try and use it to learn how it works as well.

Thanks for your kind reply/suggestions.

I added this:

function countTotalCredits() {
    var checked = [];
    $("button[data-action='multiple_select_button][data-selected=1]").closest(".video-wrapper").each(function(i){
        if ($(this).attr('data-selected') == 1) {
            checked.push($(this).attr('data-price'));
        }
    });
    return checked;
}

And then added “countTotalCredits()” to this:

function PT_MultipleBuyVideo() {
    var checked = getSelectedVideos();
    if (!checked) { return false; }

    swal({
        title: "",
        type: "info",
        html:"Simply proceed to purchase " + countSelectedVideos() + **countTotalCredits()** +" videos",
        showCancelButton: true,
        cancelButtonText: "Close",
        customClass: 'sweetalert-lg',
        confirmButtonText:'Proceed'
    }).then(function(){

and ran it without success. Probably because I’m not sure how to “sum the array”?

Any additional guidance is appreciated.

Thanks again for your reply, and link. However, I don’t know how to incorporate that into my code.

Any additional help will be appreciated

I mean… I don’t know how more I can help you. The example on that page is literally summing an array.

What part of it are you having trouble understanding or incorporating?

Thanks for your reply.

I don’t know how this:

var numbers = [65, 44, 12, 4];

function getSum(total, num) {
  return total + num;
}

function myFunction(item) {
  document.getElementById("demo").innerHTML = numbers.reduce(getSum);
}

works with this:

function countTotalCredits() {
    var checked = [];
    $("button[data-action='multiple_select_button][data-selected=1]").closest(".video-wrapper").each(function(i){
        if ($(this).attr('data-selected') == 1) {
            checked.push($(this).attr('data-price'));
        }
    });
    return checked;
}

So let me ask you a question.

What is ‘checked’ at the end of that function?

Thanks for your message.
I don’t know a lot about JavaScript. Is ‘checked’ incorrect?

Any help is welcomed

I think that he’s asking you what type of variable is that checked one. Is it a number, a string, an object, an array, a boolean, a symbol, or is it some other type?

Thanks for your reply.

I have it incorrectly. It should be more like this:

function countTotalCredits() {
    var checked = [];
    $("button[data-action='multiple_select_button][data-selected=1]").closest(".video-wrapper").each(function(i){
        if ($(this).attr('data-selected') == 1) {
            checked.push($(this).attr('data-price'));
        }
    });
}

And I have this:

function PT_MultipleBuyVideo() {
    var checked = getSelectedVideos();
    if (!checked) { return false; }

    swal({
        title: "",
        type: "info",
        html:"Simply proceed to purchase " + countSelectedVideos() + countTotalCredits() +" videos",
        showCancelButton: true,
        cancelButtonText: "Close",
        customClass: 'sweetalert-lg',
        confirmButtonText:'Proceed'
    }).then(function(){

which, when a User proceeds to purchase 2 videos, it now shows this:

“Simply proceed to purchase 2undefined videos”

I’d appreciate some assistance with the function needing to total, the cost of the selected videos, taking the cost and totaling it up with the others and then return that total value.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.