troubleshooting Question

Boss wants this small script "cleaned up" - Help needed Plz

Avatar of John S.
John S.Flag for United States of America asked on
JavaScriptjQuery
4 Comments1 Solution147 ViewsLast Modified:
I wrote a simple checkout script for our page at work. When one of the more experienced developers looked at my code, he made a comment "we need to discuss you cleaning up your code"

Ok, so I am assuming he means to re-factor it, or take a more object approach.

Can anyone help me make this look a bit more elegant?  Any help would be appreciated. Maybe I can keep him off my back tomorrow!  :)

/** Document Ready */



jQuery(function ($) {

    jQuery.ajaxSetup({
        beforeSend: function () {
            $('#mmpc-loader').show();
        },
        complete: function () {
            $('#mmpc-loader').hide();
        }
    });

    // Form Submitted
    $( "#btnPurchase" ).click( function ( e )
    {

        e.preventDefault();

        Products = (sessionStorage.getItem("product") === "") ? sessionStorage.getItem("product") : "Solopreuner";

        // Hard Code Price
        let Price = 40;

        /* API Endpoints */
        let mmpcApi = "/Product/ProcessPayment";
        let authNetApi = "/Product/ProcessPayment";

        
        let Workstations = $( "#numWorkStations" ).val();   // Qty
        let total = 40 * Workstations;

        let valid = true;  // for future use when validating

        let FirstName = $( "#firstName" ).val();
        let LastName = $( "#lastName" ).val();
        let CompanyName = $( "#companyName" ).val();
        let Title = $( "#usrTitle" ).val();
        let Email = $( "#email" ).val();
        let Address = $( "#address" ).val();
        let City = $( "#city" ).val();
        let State = $( "#state" ).val();
        let ZipCode = $("#zip").val();
        let Phone = $("#phone").val();

        let CcNum = $( "#ccnum" ).val();
        let CcExpMonth = $( "#expmonth" ).val();
        let CcExpYear = $( "#expyear" ).val();
        let CcCvv = $( "#cvv" ).val();



        //product model per device
        const ProductViewModel = function (title, price, billingCycle, quantity, recurring) {
            this.Title = title;
            this.Price = price;
            this.BillingCycle = billingCycle;
            this.Quantity = quantity;
            this.Recurring = recurring;
        };

          // Object for Authorize.NET
        var ObjAuthDotNet = {
            FirstName: FirstName,
            LastName: LastName,
            Email: Email,
            Address: Address,
            State: State,
            Zip: ZipCode,
            CardNumber: CcNum,
            ExpirationDate: CcExpMonth + "/" + CcExpYear,
            CardCode: CcCvv,
            Phone: Phone,
            Country: "USA",
            Product: new ProductViewModel(Products, Price, 1, Workstations, true)
        };

        var ObjPaymentConfirmation = {
            FirstName: FirstName,
            LastName: LastName,
            Email: Email,
            Product: sessionStorage.getItem("product"),
            ClientId: "123"  // hard code for now
        };

        // Duplicate Object For MMPC, we are going to need
        // to add data to it for our own purposes.
        var objMMPC = jQuery.extend(true, {}, ObjAuthDotNet);

        // Process the payment
        $.ajax({
            type: 'POST',
            url: mmpcApi,
            data: ObjAuthDotNet,
            dataType: 'json',
            encode: true
        })
            // promise callback
            .done(function (data) {

                console.log(data);

                // Check for Errors
                if (data.messages.resultCode === "Error") {

                    var paymentErrors = [];

                    for (var i = 0; i < data.messages.message.length; i++) {

                        // Invalid Card Number
                        if (code === "37") {
                            paymentErrors.push("You have entered an invalid card number. Please try again.");
                         // Card Declined
                        } else if (code === "145" || code === "152") {
                            paymentErrors.push("Your credit card was declined. Please try another card.");
                        // For Wells Fargo Only, Billing/Zip
                        } else if (code === "112") {
                            paymentErrors.push("Your billing state / zip code is invalid. Please try again.");
                        // Invalid Card COde
                        } else if (code === "78") {
                            paymentErrors.push("The card code you entered was incorrent. Please try again.");
                        } else {
                            /* Unspecified Error */
                            paymentErrors.push("There was an unspecified error. Please try again.");
                        }
                    }

                    // Notify User
                    alertify.alert("There was an error processing your card.");
                    return false;

  
                } else if (data.messages.resultCode === "Ok") {

                    // Successful, Send Thank You Email
                    $.ajax({
                        type: "POST",
                        url: "/Client/ThankYou",
                        data: ObjPaymentConfirmation,
                        dataType: "json"
                    });

                    // Let User Know
                    alert('Payment Successful'); // for now we'll just alert the user
                    //window.location = '/Product/ProcessPayment';  // redirect a user to another page

                } else {

                    // Unspecified Response. Report as error
                    alertify.alert('Error', 'There was an error processing your payment. Please try again.'); 
                    
                }

            });

    });

    //--------------------------------------------------

    $('#numWorkStations').on('change', function () {
        var tNumWorkstation = this.value;
        //alert(tNumWorkstation);
        UpdateProductHeader(tNumWorkstation);
        $("#total").text(40 * tNumWorkstation);

    });


    function UpdateProductHeader(wCount) {
        var prodHeaderElem = $("#productHeading");
        var headerText;

        if (wCount === 1) {
            headerText = "Solopreuner";
        }

        if (wCount >= 2) {
            if (wCount <= 50) {
                headerText = "Small Business";
            }
        }

        if (wCount > 50) {
            // Display contact modal, re-direct to contact page
            headerText = "Enterprise";
        }

        prodHeaderElem.text(headerText);
        sessionStorage.setItem('product', headerText);
    }

});
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 1 Answer and 4 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros