Using Django, how can submit a form silently and not return a HTTP response in my views as to not reload a web page when a view function is called

How can I call my view function from a button click and have it return something that would result in my web page not reloading? It seems that I must return an HTTP request in some way in views.py or I get an error. "I do not wish to stop the form submission". I would prefer not to use Ajax at this moment. I have a page with a long list of objects from my database that users can input quantities and click a button which sends the form data to a cart object. In doing this, the corresponding view function is triggered and returns some sort of HTTP Response which results in the page loading in some way. I would like it so that absolutely nothing happens when a button is clicked, other than the form data being submitted. Not even a redirect to the same page. This is because I don't want the user to lose there place on the page and have to scroll through a list of objects to find where they were.

views

def add_to_cart(request, product_id):
    return HttpResponse('')

url path

    path('cart/add/<product_id>', home_views.add_to_cart, name='add_to_cart'),

Quote

<form action="{% url 'add_to_cart' product.id %}" method="post">{% csrf_token %}</form>

3 answers

  • answered 2018-07-11 04:34 Hayden

    This effect is not maked by your Django Backed,you can post your form data by ajax request to make this result

  • answered 2018-07-11 12:06 ThatCampbellKid

    You can try something like calling post() on button click like this:

    function post() {
        $.ajax({
            type : 'POST',
            url : 'post/',  //whatever relative url you want to use
            data : { msgbox : $('#input-id').val() }, //the input id of what you are submitting
    
            success : function(json){ //do stuff if post is successful
                $('#chat-msg').val(''); //can set the to blank
            }
         });
    }
    

    Just add this to your javascript or in a script tag, but you will need to add JQuery as mentioned below:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    

  • answered 2018-07-11 12:09 AKX

    If you really don't wish to use AJAX, reload the page, or have any of the changes the POST does reflect in your page, you can add a hidden <iframe> that you set as the form's target.

    <iframe name="submit-frame" style="display: none"></iframe>
    

    ...

    <form target="submit-frame">...</form>