0

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>
juju
  • 884
  • 1
  • 9
  • 31
  • 1
    Possible duplicate of [JavaScript code to stop form submission](https://stackoverflow.com/questions/8664486/javascript-code-to-stop-form-submission) – jdigital Jul 11 '18 at 03:54
  • I don't wish to stop the form submission – juju Jul 11 '18 at 11:35

3 Answers3

1

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>
AKX
  • 152,115
  • 15
  • 115
  • 172
0

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

Hayden
  • 449
  • 4
  • 13
0

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>
ThatCampbellKid
  • 561
  • 1
  • 5
  • 19