Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

submitting a django form using javascript

ok so have this snippet of code -

    <form id="myform" name="myform" action="." method="post">
        <a href="javascript: document.forms['myform'].submit();" name="myform">Submit
        </a>
    </form>    

i am submitting a form using an href and some javascript to my django server. on the server i check the post request using the following code -

    if 'myform' in request.POST:
        '''handle the form submition'''
        return True
    return False

this returns false. any ideas why?

like image 867
ZiGiUs Avatar asked Jun 01 '26 12:06

ZiGiUs


2 Answers

here is the solution i used to solve my problem - (thank you very much fosco and adam!)

    <form id="my_form" action="." method="post">
        <a href="#" onclick="document.forms['my_form'].submit();">Call Form</a>
        <input type="checkbox" name="call_form" checked style="visibility:hidden"><br>
        <input type="submit" value="create form" style="visibility:hidden" />
    </form>`
like image 139
ZiGiUs Avatar answered Jun 03 '26 00:06

ZiGiUs


I assume "using an href" means you click a link programatically? Links always send GET requests so that's why it fails. You can submit the entire form with JS using document.forms.myform.submit(); and that will send it with POST since that's the method you specified in the form.

like image 38
Adam Bergmark Avatar answered Jun 03 '26 02:06

Adam Bergmark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!