0

I've created a cart for users to put items one wants to buy. Each item has its own id value, all prices and general info coming from MySql db. I'm outputting javascript to count quantity and final price with discounts for each model individually. Now I want to rebuild counting and it's getting hard to maintain my php code.

My questions are: 1 - what is the best practice to create JS carts with php. 2 - is there a way to simplify my code or it's better to rewrite it from 0.

        foreach ($_SESSION["gids"] as $key => $value){//for each model in session add HTML data             
        echo        "\n\t\t<hr><div class=\"row\">";

        echo        "\n\t\t\t<div class=\"2u\">";//Main photo div
        echo        "\n\t\t\t\t<span class=\"image image-full cartImg\" id=\"caseShow\">";
        echo        "\n\t\t\t\t\t<img src=\"cases/cartPics/".$value.".jpg\" id=\"caseImg\" alt=\"Чехол для iPhone 5 с орнаментом этно чехол вышиванка на iPhone\" />";
        echo        "\n\t\t\t\t</span>";
        echo        "\n\t\t\t</div>";

        echo        "\n\t\t\t<div class=\"2u\">";// name and model
        echo                linkSet('menu', 'name');
        echo        "\n\t\t\t\t<strong>";
        echo                catSet('cases', $value, 'name');
        echo        "\n\t\t\t\t<br />";
        echo                catSet('cases', $value, 'model'); 
        echo        "\n\t\t\t</strong></div>";

        echo        "\n\t\t\t<div class=\"2u\" id=\"casePriceDiv\">";//price for one item
        echo                linkSet('menu', 'priceName'); 
        echo        "\n\t\t\t\t<br /><span class=\"casePriceCart\">";
        echo                price('cases', $value);
        echo        "\n\t\t\t</span></div>";


        echo        "\n\t\t\t<div class=\"2u\">";//quantity
        echo                linkSet('menu', 'buyQty'); 
        echo        "\t\t\t\t<br /><br />";

        echo        "\n\t\t\t\t<div>";
        echo        "\n\t\t\t\t\t<label for=\"qty\"><abbr title=\"Quantity\"></abbr></label>";
        echo        "\n\t\t\t\t\t<button class=\"cartOpt cartOpt_".$value."\" onclick=\"modify_qty_".$value."(-1)\"><strong><</strong></button>";
        echo        "\n\t\t\t\t\t<input class =\"qty\" id=\"qty_".$value."\" value=\"1\" disabled=\"disabled\"/>";
        echo        "\n\t\t\t\t\t<button class=\"cartOpt cartOpt_".$value."\" onclick=\"modify_qty_".$value."(1)\"><strong>></strong></button>";
        echo        "\n\t\t\t\t</div>";
        echo        "\n\t\t\t</div>";

        echo        "\n\t\t\t<div id=\"casePriceDiv\" class=\"2u\">";//price of quantity chosen
        echo                linkSet('menu', 'buySum');
        echo        "\n\t\t\t\t - ";
        echo                linkSet('menu', 'currency'); 
        echo        "\n\t\t\t\t<br />";
        echo        "\n\t\t\t\t<strong>";
        echo                priceDisc('cases', $value);
        echo        "\n\t\t\t\t</strong>";
        echo        "\n\t\t\t\t<div id=\"sale2discCart\" class=\"sale2discCart_".$value."\"></div>";
        echo        "\n\t\t\t</div>";

        print       "<script>
                        function modify_qty_".$value."(val) {
                            var qty = document.getElementById('qty_".$value."').value;
                            var new_qty = parseInt(qty,10) + val;
                            if (new_qty < 1) {
                                new_qty = 1;
                            }else if(new_qty > 5){
                                new_qty = 5;
                            }
                            document.getElementById('qty_".$value."').value = new_qty;
                            document.getElementById('qtyForm_" .$value."' ).value = new_qty;
                            return new_qty;
                        };

                        $(document).ready(function(){
                            var itemPrice = 0;
                            $('#itemPrice_".$value."').each(function(){
                                itemPrice += parseInt($(this).text(),10);

                                $('.cartOpt_".$value."').click(function(){
                                    var new_qty = ($('#qty_".$value."').val());
                                    var totalItemPrice = new_qty * itemPrice;
                                    $('#itemPrice_".$value."').html(totalItemPrice);
                                    productsInCart();
                                });
                            });

                        function productsInCart(){
                            var inCart = 0;
                            var finalPrice;
                            $('.qty').each(function(){
                                inCart += parseInt($(this).val());
                            });

                            if(inCart<2){
                                var total = 0;
                                $('.itemPrice').each(function(){
                                    total += parseInt(this.innerHTML);
                                });
                                $('#overallPrice').text(total);
                                document.getElementById('priceForm_" .$value."' ).value = total;
                                $('.itemPrice').css('text-decoration','none').addClass;
                                $('#sale2discCart').empty();
                                $('.totalDisc').hide();

                                finalPrice = total;
                            }else{
                                var totalNet = 0;
                                var total = 0;
                                var totalDisc =0;
                                var sale2disc = \"-30%\";
                                var sale2price = $('.itemPrice');
                                var new2Price = 0;
                                $('#itemPrice_".$value."').each(function(){
                                    new2Price += parseInt(this.innerHTML)* 0.7;
                                    new2Price = Math.round(new2Price);
                                    document.getElementById('priceForm_" .$value."' ).value = new2Price;

                                    $(this).css('text-decoration','line-through').addClass;
                                    $(this).css('letter-spacing','1px').addClass;
                                    $('.sale2discCart_".$value."').html(sale2disc);
                                    $('.sale2discCart_".$value."').append('<br /><br /><span style=\"text-decoration:line-through\">');
                                    $('.sale2discCart_".$value."').append(new2Price);
                                    $('.sale2discCart_".$value."').append('</span><br />');
                                });
                                $('.itemPrice').each(function(){
                                    totalNet = parseInt(this.innerHTML);
                                    totalDisc += totalNet * 0.3;
                                    total += totalNet * 0.7;
                                    total = Math.round(total);
                                    totalDisc = Math.round(totalDisc);
                                    finalPrice = total;
                                });

                                $('#overallPrice').text(total);
                                $('.totalDisc').show();
                                $('#totalDisc').text(totalDisc).append('.00');
                            }

                            var delCost = $('.delCost').val();
                            finalPrice =  parseInt(finalPrice, 10) + parseInt(delCost, 10);
                             document.getElementById('finalPrice' ).value = finalPrice;
                        }
                        productsInCart();
                        })

                    </script>";

        echo        "\n\t\t\t<div class=\"2u\">";
        echo                linkSet('menu', 'caseDel'); 
        echo        "\t\t\t\t\t<br /><br />";
        echo        "\n\t\t\t\t<label for=\"del\"><abbr title=\"Delete\"></abbr></label>";
        echo        "\n\t\t\t\t<form name =\"unsetCase\" method =\"POST\" action = \"includes/unsetCartModel.php\">";
        echo        "\n\t\t\t\t<button class=\"cartOpt\" name=\"unsetCase\" type=\"submit\" value=".$key."><strong>X</strong></button>";
        echo        "\n\t\t\t\t</form>";
        echo        "\n\t\t\t</div>";

        echo        "\n\t\t</div>\n\n";
        };
2
  • Why are you so worried about html formatting? What is with all the \n's and \t's? Commented Nov 25, 2013 at 20:15
  • \n\t - are for formatting html code, new lines and tabs, for source to be viewed from inside the browser, not to let everything stick together. Commented Nov 25, 2013 at 20:20

1 Answer 1

1

I'm not really sure if that is the way you should follow. IMO you should place id of your product somewhere (like data-id attribute on element), load it via onclick event on button "add to cart" and send a request via ajax to php script that adds it to your cart (which is maintained by session or cookies). In response from your ajax call you should receive product information that you store and display to your user.

Also if you want to print html code via php, you should use output buffers - just start one with ob_start() and collect the output via ob_end_clean() :)

Sign up to request clarification or add additional context in comments.

1 Comment

I just read about output buffering. Nice for static html. But I'm using php variables thru all my html (dynamic) code. Can't see if it's possible with output buffering. Items are added to cart only on click from user. but to manage quantity and prices/discounts I need to control each item with it's own id: value. thats why I'm outputting JS for each item with php.Maybe ajax is the decision. need to learn more about it. is there any worth reading articles about carts on ajax?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.