How to get the total value of this payments method - javascript

Tried so many methods but did not work how can I get it total from the client side JavaScript to the payment gateway
function() {
    // VARS
    const productsContainer = document.querySelector("#grid");
    const cartContainer = document.querySelector("#shopping-cart");
    const cartContent = document.querySelector("#cart-content");
    const toggleCartBtn = document.querySelector("#toggle-cart-btn");
    const clearCartBtn = document.querySelector("#clear-cart");
    const checkoutBtn = document.querySelector("#checkout-btn");
    const totalPriceContainer = document.querySelector("#total-price");
    // FUNCTIONS
    function toggleCart() {
        // toggle shopping cart visibility
        cartContainer.classList.toggle("open");
    }
    function getLSContent() {
        // get contents from local storage.
        // if nothing is there, create an empty array
        const lsContent = JSON.parse(localStorage.getItem("products")) || [];
        return lsContent;
    }
    function setLSContent(lsContent) {
        // save content inside local storage
        localStorage.setItem("products", JSON.stringify(lsContent));
    }
    function calculateTotal(prices) {
        // calculate the total price in the cart
        return prices.reduce(function(prev, next) {
            return prev + next;
        }, 0);
    }
    function getCartItemPrices() {
        // extract the price numbers from the cart items to calculate total
        const prices = [];
        // retrieve the td element in the cart where the product price is stored
        // for each product in the cart
        let nums = cartContent.querySelectorAll("tr td:nth-child(3)");
        // iterate over each td node and extract the price
        // strip the $ sign from the text, turn the string into
        // a number and push the number into the prices array
        if (nums.length > 0) {
            for (let cell = 0; cell < nums.length; cell++) {
                let num = nums[cell].innerText;
                num = num.replace(/[^\d]/g, "");
                num = parseFloat(num);
                prices.push(num);
            }
            // return the prices array
            return prices;
        } else {
            return;
        }
    }
Where the cart total is been displayed in inner html shopping cart
    function displayCartTotal() {
        // display the total cost in the cart
        const prices = getCartItemPrices();
        let total = 0;
        if (prices) {
            total = calculateTotal(prices);
            totalPriceContainer.innerHTML = `<span class="total">Total: $${total.toFixed(
        2
      )}</span>`;
        } else {
            totalPriceContainer.innerHTML = '<span class="total">Total: $0</span>';
        }
    }
Not that necessary thou
    function displayProducts() {
        // display all products in the cart
        // get contents from local storage
        const lsContent = getLSContent();
        let productMarkup = "";
        // if local storage is not empty, build the
        // cart items markup and the appropriate details
        if (lsContent !== null) {
            for (let product of lsContent) {
                productMarkup += `
          <tr>
          <td><img class="cart-image" src="${product.image}" alt="${
          product.name
        }" width="120"></td>
          <td>
            ${product.name}
          </td>
          <td>${product.price}</td>
          <td>X</td>
          </tr>
        `;
            }
        } else {
            // if no content is in local storage, alert user
            productMarkup = "Your cart is empty.";
        }
        // add markup to DOM
        cartContent.querySelector("tbody").innerHTML = productMarkup;
    }
    function saveProduct(clickedBtn) {
        // save selected product in local storage and display it in the cart together
        // vars
        const productId = clickedBtn.getAttribute("data-id");
        const card = clickedBtn.parentElement.parentElement;
        const cardInfo = clickedBtn.parentElement;
        const prodImage = card.querySelector("img").src;
        const prodName = cardInfo.querySelector("h4").textContent;
        const prodPrice = cardInfo.querySelector(".card__price").textContent;
        let isProductInCart = false;
        // get local storage array
        const lsContent = getLSContent();
        // to avoid user adds the same course twice, check
        // the product is not in LS already before adding it
        lsContent.forEach(function(product) {
            if (product.id === productId) {
                alert("This course is already in your cart.");
                isProductInCart = true;
            }
        });
        // only if the product is not already in the cart,
        // create an object representing selected product info
        // and push it into local storage array
        if (!isProductInCart) {
            lsContent.push({
                id: productId,
                image: prodImage,
                name: prodName,
                price: prodPrice
            });
            // add product into into local storage
            setLSContent(lsContent);
            // update the display of courses in the shopping cart
            displayProducts();
        }
    }
    function removeProduct(productId) {
        // remove product from cart (and from local storage)
        // retrieve list of products from LS
        const lsContent = getLSContent();
        // get the index of the product item to remove
        // inside the local storage content array
        let productIndex;
        lsContent.forEach(function(product, i) {
            if (product.id === productId) {
                productIndex = i;
            }
        });
        // modify the items in local storage array
        // to remove the selected product item
        lsContent.splice(productIndex, 1);
        // update local storage content
        setLSContent(lsContent);
        displayProducts();
    }
    function clearCart() {
        // clear all products from cart (and local storage)
        // retrieve list of products from LS
        const lsContent = getLSContent();
        // empty array in local storage
        lsContent.splice(0, lsContent.length);
        // update local storage
        setLSContent(lsContent);
        // display cart content again
        displayProducts();
    }
    function checkout() {
        // checkout: just clear the cart
        // after user confirms the checkout process
        const cartProducts = cartContent.querySelector("tbody").innerHTML;
        if (cartProducts !== "" && confirm("Are you sure you want to checkout?")) {
            clearCart();
        } else {
            return;
        }
    }
    // BIND EVENTS AND CALL FUNCTIONS
    // Page load:
    document.addEventListener("DOMContentLoaded", function(e) {
        // display list of products in cart, if any, on page load
        displayProducts();
        // display cart total
        displayCartTotal();
    });
    // open and close shopping cart
    // when cart button is clicked
    toggleCartBtn.addEventListener("click", function(e) {
        e.preventDefault();
        toggleCart();
    });
    // Save product in cart and Local Storage
    // when add to cart button is clicked
    productsContainer.addEventListener("click", function(e) {
        if (e.target.classList.contains("add-to-cart")) {
            e.preventDefault();
            const clickedBtn = e.target;
            saveProduct(clickedBtn);
        }
    });
    productsContainer.addEventListener("click", function(e) {
        if (e.target.classList.contains("add-to-cart")) {
            displayCartTotal();
        }
    });
    // bind removeProduct to click event of the cartContent table
    cartContent.querySelector("tbody").addEventListener("click", function(e) {
        e.preventDefault();
        // identify the button that was clicked
        const clickedBtn = e.target;
        // if it's a remove button
        if (e.target.classList.contains("remove")) {
            // get the value of the data-id property, which contains the
            // id of the selected product
            const productId = clickedBtn.getAttribute("data-id");
            // use the id to remove the selected product
            removeProduct(productId);
            // display products in the cart again,
            // now the list should be displayed with 1 less product
            // or empty if no products are left in the cart
            // adjust the total
            displayCartTotal();
        }
    });
    // bind the button to clear the cart both to the function that
    // clears the cart and to the function that adjusts the total price
    clearCartBtn.addEventListener("click", function(e) {
        e.preventDefault();
        clearCart();
    });
    clearCartBtn.addEventListener("click", displayCartTotal);
    // bind the button that does the checkout both to the function that
    // controls the checkout and and to the function that adjusts the total price
The checkout button for the payment gateway in client side JavaScript
checkoutBtn.addEventListener("click", function(e) {
        e.preventDefault();
        checkout();
        const totalPriceContainer = document.querySelector("#total-price");
        function displayCartTotal() {
            // display the total cost in the cart
            const prices = getCartItemPrices();
            let total = 0;
            if (prices) {
                total = calculateTotal(prices);
                totalPriceContainer.innerHTML = `<span class="total">Total: $${total.toFixed(
            2
          )}</span>`;
            } else {
                totalPriceContainer.innerHTML = '<span class="total">Total: $0</span>';
            }
        }
        var handler = PaystackPop.setup({
            key: 'pk_test_39c6a15c308d31ca0c6a2973e9d52b79177b2262',
            email: "sipboyjohn#gmail.com",
            amount: prices * 100,
            currency: 'NGN', // Use GHS for Ghana Cedis or USD for US Dollars
            ref: 'YOUR_REFERENCE', // Replace with a reference you generated
            callback: function(response) {
                //this happens after the payment is completed successfully
                var reference = response.reference;
                alert('Payment complete! Reference: ' + reference);
                // Make an AJAX call to your server with the reference to verify the transaction
            },
            onClose: function() {
                alert('Transaction was not completed, window closed.');
            },
        });
        handler.openIframe();
    });
    checkoutBtn.addEventListener("click", displayCartTotal);
})();
The html code for the shopping cart
 <div id="shopping-cart" class="shopping-cart-container">
                                <table id="cart-content">
                                    <thead>
                                        <tr>
                                            <th>Image</th>
                                            <th>Name</th>
                                            <th>Price</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody></tbody>
                                </table>
                                <p class="total-container" id="total-price" name="price"></p>
                               
                                <button type="submit"  id="checkout-btn" class="cart-btn">Checkout </button>
                               
                                Clear Cart
                             
                            </div>

Related

add class onscroll depending on element on screen

I'm trying to add an active class to the navigation bar to the section currently in-view using JS
this function adds the section in-view to the browser URL
function CheckScroll(el) {
var top_of_object = el.offset().top;
var bottom_of_window = $(window).scrollTop() + $(window).height();
if (bottom_of_window >= top_of_object) {
// window.location.hash = '#'+ el.attr('id');
history.replaceState(null, document.title , '#' + el.attr('id'));
}
$(window).scroll(function(){
$('.scrollhelp').each(function() {
CheckScroll($(this));
});
});
this function is where i'm stuck, i dont know how to tell it to check for the hashSlicer value inside the array of lists and if it matches one of them, give it active class!
let section = document.querySelectorAll('.scrollhelp');
        let lists = document.querySelectorAll('.product-page-header-sections h6');
        function activeLink(li) {
            lists.forEach((item) => item.classList.remove('active'));
//             li.classList.add('active');
            var hash = li;
//             var hashSlicer = hash.replace('#' , '', '-header', '');
            var hashSlicer = hash.slice(1,-7);
// console.log(hashSlicer);
for (i = 0; i<lists.length; i++) {
while (lists[i].innerText == hashSlicer) {
console.log('hey');
}
}
        }
        lists.forEach((item) =>
            item.addEventListener('click', function(){
                activeLink(this);
            }));
window.onscroll = () => {
           section.forEach(sec => {
                let top = window.scrollY;
                let offset = sec.offsetTop;
                let height = sec.offsetHeight;
                let id = sec.getAttribute('id');
                if (top >= offset && top < offset + height) {
//                     const target = document.querySelector("[href='#${id}']").parentElement;
                    const target = window.location.hash;
                    activeLink(target);
//                     console.log(target);
                }
            })
        };
LINK for the PAGE!
https://petitbebe.store/product/stroller-perefix/

how to import javascript class into electron app

I have a file, f1.js, that i will like to use in another f2.js.
f1.js
import firebase from 'firebase';
const config = {
apiKey: "your api key here",
authDomain: "xxxxx.firebaseapp.com",
databaseURL: "https://xxxxx.firebaseio.com"
};
firebase.initializeApp(firebaseConfig);
export const firebase_auth = firebase.auth;
export const firebase_db = firebase.database();
export const firebase_functions = firebase.functions()
f2.js
import { firebase_auth,firebase_functions,firebase_db } from "../services/f1";
module.exports = class authManager {
constructor(data) {
}
}
I want to use the authManager class from f2.js in an electron render window f3.html. Here is the f3.html file and my attempt to call the authManager
f3.html
<script>
    const { PythonShell } = require('python-shell');
    const { ipcRenderer } = require('electron');
    const loadBalancer = require('electron-load-balancer');
    const path = require('path');
    // const { helper } = require('../utils/postProcessor.js');
    const log = require('electron-log');
    // 1. Tell PythonShell which script to run for this background task
    let pyshell = new PythonShell(path.join(__dirname, '/../scripts/process1.py'), {
        pythonPath: 'python3',
    });
    log.info('Python spawned:', pyshell && pyshell.command);
    PROCESS_NAME = 'process 1';
  loadBalancer.job(
        ipcRenderer,
        PROCESS_NAME,
        () => {
pyshell.on(
                'message',
          function (results) {
             
                    try {
                        const parsedJSON = JSON.parse(results);
                        const barcode = parsedJSON["result"]
                        const serial = parsedJSON["serial"]
                       
                      const signin = new authManager(serial)
                        const auth_status = signin.authenticate()
                       
                       
                    } catch (error) {
                        log.error(error);
                    }
                });
        },
        () => {
            // 6. Cleanup PythonShell when cleanup callback called
            pyshell.terminate();
        },
    );
   
   
I tried calling the authManager using different methods such as
const authManager = require('/../helpers/f2.js')
none of them seem to work.
What is the proper way to call the authManager in f3.html

Manually drilldown highcharts

I have a chart with multiple level drilldowns.
Given series id I would like to drilldown to the corresponding using a function like
function drilldown(id) {
// function drills down to the series having id
}
Is it possible to do this?
You can fire an event manually like this:
chart.series[0].points[0].hcEvents.click[0]();
Try this example: http://jsfiddle.net/kkulig/mqnyy9cu/
Is it possible to do this?
Yes
This is the sample code
   
chartConfig.chart.events.drilldown = function(e) {
                if (!e.seriesOptions) {
                    var chart = this,
                        drilldowns = drillDownColumChartData,
                        drilldowns2 = drillDownLinChartData,
                        columnSeries = drilldowns[e.point.drilldown],
                        lineSeries = drilldowns2[e.point.drilldown];
    
                    setTimeout(function() {
                        /*https://github.com/highcharts/highcharts/issues/2989*/
                        if (e.point.x != null) {
                            chart.addSingleSeriesAsDrilldown(e.point, columnSeries);
                            chart.addSingleSeriesAsDrilldown(e.point, lineSeries);
                            chart.yAxis[1].setTitle({
                                text: secondaryYaxisTitle
                            })
                            chart.applyDrilldown();
                        }
                    }, 0);
                }
            };
You can get the selected point details from e.point
Refer Highcharts asyc drilldown

Get number for Cortana in JS Hosted Web app

I'm trying to get Cortana to work in my Hosted Web App. However, I'm stumbeling into an issue where I don't get the text the user has spoken to Cortana. Here is what should happen:
If the user says "ChangeWindows show build 14393" the app should open and navigate to the address "/build/14393". However, I'm not sure how to get that number. Here's the code I have right now:
The vcd.xml
<?xml version="1.0" encoding="utf-8"?>
<VoiceCommands xmlns="http://schemas.microsoft.com/voicecommands/1.2">
<CommandSet xml:lang="en-us" Name="ChangeWindowsPreview">
<CommandPrefix>ChangeWindows</CommandPrefix>
<Example>Navigate to a changelog, milestone or build</Example>
<Command Name="OpenBuild">
<Example>Show build 14393</Example>
<ListenFor RequireAppName="BeforeOrAfterPhrase">Show [build] {build}</ListenFor>
<Feedback>Opening build {build} with ChangeWindows</Feedback>
<Navigate />
</Command>
<Command Name="OpenNext">
<Example>Show the next major release</Example>
<ListenFor RequireAppName="BeforeOrAfterPhrase">Show [the] next [major] [feature] [release]</ListenFor>
<Feedback>Opening vNext with ChangeWindows</Feedback>
<Navigate />
</Command>
<PhraseTopic Label="build" Scenario="Dictation"></PhraseTopic>
</CommandSet>
</VoiceCommands>
And for my JS I have:
    <script type="text/javascript">
    if ( typeof Windows !== 'undefined' ) {            
        var activation = Windows.ApplicationModel.Activation;
        
       Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (args) {
            if ( args.kind === activation.ActivationKind.voiceCommand ) {
                var speechRecognitionResult = args.result;
                if ( speechRecognitionResult.rulePath[0] === "OpenBuild" ) {
                    console.log( "Opening this build from Cortana: " + speechRecognitionResult.text );
                    window.location.replace( "/build/" + speechRecognitionResult.text );
                }
                if ( speechRecognitionResult.rulePath[0] === "OpenNext" ) {
                    console.log( "Opening next feature release with Cortana" );
                    window.location.replace( "/build/next" );
                }
            }
        })
}
   </script>
So, obviously, 'speechRecognitionResult.text' is not what I'm looking for here. I hoped someone however knows should be there to get {build}.

jQuery Google Analytics tracking

I am trying to use jQuery to track downloads and other events on the webpage. It is difficult to debug this. The code below is not currently working. Assume the page has the jQuery library loading, and all of the XXXX's are replaced with the correct info. Any ideas? MUCH APPRECIATED!
<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXX']);
    _gaq.push(['_setDomainName', 'XXXXX.com']);
    _gaq.push(['_addIgnoredRef', 'XXXXX.com']);
    _gaq.push(['_trackPageview']);
    if (jQuery) {
        jQuery(document).ready(function () {
            jQuery('a').click(function () {
                var $a = jQuery(this);
                var href = ($a.attr('href')) ? $a.attr('href') : '';
                if ((href.match(/^http/i)) && (!href.match(document.domain))) {
                    var category = 'outgoing - XXXX Landing';
                    var event = 'click - XXXX Landing';
                    _gaq.push(['_trackEvent', category, event, href]);
                } else {
                    if (href.match(/.(doc|pdf|xls|ppt|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)$/i)) {
                        var category = 'download - XXXX Landing';
                        var event = 'click - XXXX Landing';
                        _gaq.push(['_trackEvent', category, event, href]);
                    } else {
                        if (href.match(/^mailto:/i)) {
                            var category = 'mailto - XXXX Landing';
                            var event = 'click - XXXX Landing';
                            _gaq.push(['_trackEvent', category, event, href]);
                        }
                    }
                }
            });
        });
    }
    (function () {
        var ga = document.createElement('script');
        ga.type = 'text/javascript';
        ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        if ('http:' == document.location.protocol) {
            ga.src = 'http://www.google-analytics.com/ga.js';
        } else {
            ga.src = 'https://ssl.google-analytics.com/ga.js';
        }
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(ga, s);
    })();
</script>
Google Analytics has Event Tracking built in.
For example, if you're trying to track a file download you could do something like this --
HTML:
Click to download.
JS:
$("a.download").click(function() {
_gaq.push(['_trackEvent', 'Files', 'Downloaded'])
});
Here is Google's official Event Tracking Guide. The guide will explain everything in much more detail for you.
I'd probably use $.getScript to download and apply the GA code to the DOM rather than the long form stuff they give you as boilerplate. You'll also need that in the DOM before running the stuff where you set the tracking code, domain etc or _gaq won't be doing anything.

Categories

Resources