I am trying to submit my form with javascript but its send me GET
in backend. While i expect to receive POST
request
<form id="my_form" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="number" name="conf" >
<a onclick="document.getElementById('my_form').submit();" href="{% url 'signup' 0 %}">ارسال کد</a>
<br><br>
<button type="submit">ثبت نام</button>
</form>
"GET /signup/0 HTTP/1.1" 200 1531
The output I expect
"POST /signup/0 HTTP/1.1" 200
I believe your issue is the following line
<a onclick="document.getElementById('my_form').submit();" href="{% url 'signup' 0 %}">Send Code</a>
Because it’s a link, the browser will handle it’s click. You’d need to add return false;
to your click handler to stop the browser following the link, or event.preventDefault()
.
Maybe it’s worth mentioning that the href
attribute will not do anything then. Except for making the <a>
a real link, focusable and can be activated.
<a onclick="document.getElementById('my_form').submit(); return false;" href="{% url 'signup' 0 %}">Send Code</a>
But in any case, a button would be more appropriate, since you are submitting the form as well.
Your href
attribute and link text make it seem like you want to still submit the form, but take a different action when clicking “Send Code”. For this purpose HTML suggests using several submit buttons with different names, that then can be differentiated on the server.
Or you can add the formaction
attribute to the button to send the form to a different URL.
<form id="my_form" method="post">
{% csrf_token %}
{{form.as_p}}
<label for="conf">Code</label>
<input type="text" id="conf" name="conf" inputmode="numeric" pattern="\d+">
<button type="submit" name="send_code">Send Code</button>
OR
<button type="submit" formaction="{% url 'signup' 0 %}">Send Code</button>
<br><br>
<button type="submit" name="submit">Login</button>
</form>
Note also that I added a label to the code field, since every input needs a label. And I changed the input type for the code, as type="number"
is not the right input type for codes. The following will make sure on-screen keyboards will be optimised to enter numbers and provide some hints to improve usability.
<label for="conf">Code</label>
<input type="text" id="conf" name="conf" inputmode="numeric" pattern="\d+" size="6" placeholder="123456">