3

I've created a add-to-cart in my website and it works just great.

Am using Jquery.getJSON to make the request to get the value of the chosen product, here is the code:

    $(function() {
      $('a#process_menu').bind('click', function() {
        /*var amount = document.getElementById('kale').value;*/
        $.getJSON('{{url_for("get_the_order")}}', {
          menu_order: $(this).text(), price_order: $('input[name="kalkal"]').val(),
        }, function(data) {
          location.reload();
        });
        return false;
      });
    });

and here is the function that receiving the request:

@app.route('/get_the_order')
def get_the_order():

    global the_order_list

    try:

        the_order_list = []
        sum_list = []

        get_order = request.args.get('menu_order', 0, type=str)
        get_price = request.args.get('price_order', 0, type=str)

        the_order_list.append(get_order)
        sum_list.append(get_price)

        session['theOrder'] = ' '.join(the_order_list)
        session['price'] = ' '.join(sum_list)

        return jsonify(result=the_order_list + sum_list)

    except Exception as e:
        return redirect("menu")

and here i have the template that shows all the products:

{% if entries_menu %}
    {% for menu_ent in entries_menu %}
        <div class="col-sm-6 col-md-3 col-lg-3 {{menu_ent.categorie}}">
            <div class="portfolio-item">
                <div class="hover-bg">
                    <a id="process_menu">
                        <div class="hover-text">
                            <h4 id="title">{{menu_ent.title}}</h4>
                            <small id="price">{{menu_ent.price}}</small>
                            <div class="clearfix"></div>
                            <i class="fa fa-plus add_basket"></i>
                            <div class="counter-order">
                                <div class="row">
                                    <div class="col-md-3">
                                        <form>
                                            <fieldset>
                                                <div class="form-group">
                                                    <input id="kale" name="kalkal" class="form-control" type="number" value="1" min="1" max="999" />
                                                </div>
                                            </fieldset>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <img src="../../static/{{menu_ent.path}}" class="img-responsive" alt="..." id="image-menu">
                    </a>
                </div>
                <h4 class="brand bold">{{menu_ent.title}}</h4>
                <span class="price pull-right">{{menu_ent.price}} </span><span class="amount pull-right"> {{menu_ent.amount}}</span>
                <p id="descr">{{menu_ent.descr}}</p>
            </div>
        </div>
    {% endfor %}
{% endif %}

here i made this function to put all the products within array and showing them above where the cart exist beside the header, this is the file where all the logic happens also where it should show what i want:

        {% if session.logged_in %}

            {% if session.theOrder %}
                <div class="confirm-cancel">
                    <a href="{{url_for('flush')}}"><i class="fa fa-close fa-3x btn-danger"></i></a>
                    <a href="{{url_for('order_dish')}}"><i class="fa fa-check fa-3x btn-success"></i></a>
                </div>
            {% endif %}

            <li class='main'><a href='/#main'><span>Main</span></a></li>
            <li class="comfort"><a href='/#ckidki' ><span>Chief</span></a></li>
            <li class="menu"><a href='/menu/' ><span>Menu</span></a></li>
            <li class="order"><a href="/order/" ><span>Make an order</span></a></li>
            <li class="contact"><a href='/#contact' ><span>Contact us</span></a></li>
            <li class="last orders"><a href='/admin/' ><span>Admin</span></a></li>

            {% if session.theOrder %}

                <li class="basket"><i class="fa fa-shopping-basket fa-3x" style="color: #fff;"><p class="pull-left" id="bask" style="font-size: 19px; font-weight: 600; font-family: "Russo One",sans-serif;">{{session.get('theOrder')}} &nbspx{{session.get('price')}}</p></i></li>

            {% else %}

                <li class="basket"><i class="fa fa-shopping-basket fa-3x" style="color: #fff;"><p class="pull-left" id="bask" style="font-size: 19px; font-weight: 600; font-family: "Russo One",sans-serif;">0$ &nbsp&nbsp</p></i></li>

            {% endif %}
        {% endif %}

The problem is i can't get all the products that i've been chosen inside the session, so if i checked the products list i see only one, in fact , am getting only the clicked item every time.

Please, any suggestion how to make that work, anyway please, any help would be tons appreciated .

Paolo Casciello
  • 7,982
  • 1
  • 43
  • 42
Reznov
  • 175
  • 1
  • 3
  • 14
  • Arrays can be passed in the session object. Global variables don't work well for this sort of thing. A session variable is like global variable. So use that for `the_order_list`. Hint: check if a session variable has been declared in the view function. If not, declare it. Then, you effectively have a global variable via the session object. Also, why the `try` `except` block, that seems troublesome. Please keep in mind; [minimal, complete and verifiable](http://stackoverflow.com/help/mcve) code examples when posting. – wgwz Jan 06 '16 at 18:33
  • i declared the session and it worked, thanks :) . – Reznov Jan 07 '16 at 09:59
  • You can directely change the session with extend : https://stackoverflow.com/questions/61415988/flask-storing-get-and-update-list-in-session-using-flask-session – Romain May 31 '22 at 13:42

2 Answers2

5

I modified your code like this:

    the_order_list = session['theOrder']
    sum_list = session['price']

    the_order_list.append(get_order)
    sum_list.append(get_price)

    session['theOrder'] = the_order_list
    session['price'] = sum_list
naghmeh
  • 97
  • 1
  • 8
  • this solution works, but up to a specific length of the list, after that you'll get a UserWarning: The "b'session'" cookie is too large, as the default limit is 4093 bytes. – BHA Bilel May 14 '20 at 21:30
5

I was facing the same issue and finally got this answer!

@app.route('/addtocart/')  #加入购物车选项
def addtocart():
id = request.args.get('id')
if 'cart' not in session:
    session['cart'] = []  # 
cart_list = session['cart']
cart_list.append(id)
session['cart'] = cart_list  # 
print(session)

cart_list = session['cart'] will return an empty list. Then, after cart_list.append(id), you've got a list with length 1. The key sentence is session['cart'] = cart_list, if you don't do this, your list's maximum length is 2.

Leopold Joy
  • 4,524
  • 4
  • 28
  • 37
Lei Sen
  • 187
  • 2
  • 6
  • Ok cart_list = session['cart'] will return a empty list. then, after cart_list.append(id), you got a list with length 1. the key sentense is session['cart'] = cart_list # if you dont do this, your list maxium length is 2. – Lei Sen Dec 18 '17 at 06:26