简体   繁体   中英

Django - Pass data from javascript to view & redirect to a new url

On my webpage there are 2 buttons - A & B. I want to capture the button clicked by the user in front end & send it back to the server so that I can generate the appropriate token for the user. Then redirect the user to the right url - "/A" or "/B" depending on what they clicked.

urls.py

    path('buttonTest/', buttonView), # Initially testing with one url

Views.py

def buttonView(requests):
    if requests.method == 'POST':
        clicked_button_val = requests.POST.get('clicked_button')
        # generate auth token
        render(requests, 'test.html')

test.html

<form id="testform">
    <button name="subject" id="A" type="submit" value="A">A</button>
    <button name="subject" id="B" type="submit" value="B">B</button>
</form>
<script>
$("button").click(function() {
    $.ajax({
        type: "POST",
        data: { 
            "clicked_button": $(this).val(),
        },
        success: function(result) {
            alert('ok');
        },
        error: function(result) {
            alert('error');
        }
    });
});
</script>

I am able to successfully pass the data from front-end to views. But the url doesn't redirect to /buttonTest. If I add redirect in html like this,

<button name="subject" id="A" type="submit" value="A" onclick="location.href='/buttonTest'">A</button>

then the request in views.py becomes a GET request & is not able to access what the user clicked.

What I want to do is capture the button clicked by user via a POST request & then redirect the user to a new url & pass the data captured in the POST request to the new url & view.

Most likely your ajax request is not even used, because your buttons have type="submit" and you never prevent the form submission. The simplest method would be to set a different name attribute on both the buttons and forego using JavaScript:

<form id="testform">
    <button name="submit_A" id="A" type="submit" value="A">A</button>
    <button name="submit_B" id="B" type="submit" value="B">B</button>
</form>

Now in the view:

def buttonView(request): # request should be singular(naming convention)!!
    if request.method == 'POST':
        if 'submit_A' in requests.POST:
            # generate auth token for button A and redirect
        elif 'submit_B' in requests.POST:
            # generate auth token for button B and redirect
        render(requests, 'test.html')

You cannot include data in a redirect since a redirect triggers a GET request.

You can however add a formaction attribute to submit inputs to submit the same form to different URLs

<input type="submit" formaction="/handle-a/" value="A">
<input type="submit" formaction="/handle-b/" value="B">

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