简体   繁体   中英

How do I use submit form button without refreshing the page?

I have a function in views.py which takes input (through the post-request on an HTML page) and appends it to a list and then returns the newly appended list. Upon submitting, the whole page refreshes. I have a background element (a video on a loop).

In my HTML file, I have changed the button type from type="submit" to type="button", which prevents the page from re-loading and continues to play background video correctly. However, it doesn't seem to run my main function. I thought maybe using type="button" and then making a to run the function might work, but I might be wrong on that. I have read solutions others have posted with Javascript and AJAX; I tried to copy and paste some but without success. I am new to programming and would really appreciate feedback and help! Thanks Tobias

in views.py :

def test5(request):
    pd = [8, 24, 'kb']
    user_data = {}

    if request.method == 'POST':

        x = request.POST.get('x') 

        pd.append(x)

    return render(request,'app/test5.html',{'data': pd})

in test5.html :

{% extends 'app/testbase.html' %}  <!-- this brings in my background video -->

{% block content %}

This is a test<br>
[8, 24, 'kb'] <br>

<script>
    function click_action()  {
    }
</script>

<form method="post" action="/app/test5/" id="post-form">
    {% csrf_token %}

    <input name="x" placeholder="Enter number" value="" required autofocus>

    <button onclick="click_action()" name="start_button" id="myBtn" type="submit">add to list </button>
</form>

{{ data }}

{% endblock %}

I would like to get the newly appended list (pd) printed on the screen without the page being refreshed after hitting the button. Thanks for the help!!!!

Write your form as follows:

<form id="post-form">
    {% csrf_token %}

    <input id="idName" name="x" placeholder="Enter number" value="" required autofocus>

    <button onclick="click_action()" name="start_button" id="myBtn" type="button">add to list </button>
</form>

put the following code inside your click_action() function

$('#myBtn').click(function(){
    var name=$("#idName").val();

    $.ajax({
        url: "/app/test5/",
        method: "POST", 
        data: {"name": name}, 
        success: function (data) {        
            // Show a pop up on success
        }
    });
});

In your views.py script's function, if you write return render(request,'app/test5.html',{'data': pd}) at the end of the function like yours, it'll always redirect after execution this view function. So, try avoiding this and use JsonResponse(status = 200, data = {'success' : 1}) .

So, in your views.py

from django.http.response import JsonResponse


def test5(request):
    pd = [8, 24, 'kb']
    user_data = {}

    if request.method == 'POST':

        x = request.POST.get('x') 

        pd.append(x)

    return JsonResponse(status = 200, data = {'success' : 1})

First, your page is reloading because that is the default behavior of the forms when you click on submit, you can prevent that using: e.preventDefault()

You can use this code:

<script>
    function submit_action(event)  {
        event.preventDefault();  // to prevent the page reload (and the submit also)

        let number = $("#numberInput").val();

        $.ajax({
           url: "/app/test5/",
           method: "POST", 
           data: {"x": number}, 
           success: function (data) {        
               // here you receive the data and you need "manually" update the template
               console.log(data);
           }
       });
    }
</script>

<form method="post" action="/app/test5/" id="post-form" onsubmit="submit_action(event)">
    {% csrf_token %}

    <input id="numberInput" name="x" placeholder="Enter number" value="" required autofocus>

    <button type="submit">add to list </button>
</form>

You need to have included JQuery in this code, you can learn it here if you don't know how

I guess you are just playing with this code, the best way to add a number to a list is just use javascript and DOM manipulation unless you need store the value in a database o something like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM