I'm developing my Django application and I would like to use JavaScript in order to improve my website.
I have a form and I would like to display 2 things :
It's the first time I'm using JS and I need help to make this process.
This is my code :
<form class = "form" method='POST' action=''> {% csrf_token %}
<br></br>
{{ form.as_p}}
<br></br>
<button type="submit">Valider</button>
</form>
<script>
$('#form').submit(function() {
var c = confirm("Click OK to continue?");
return c; //you can just return c because it will be true or false
});
</script>
And if my form is valid and saved :
<script type="text/javascript" >
$(document).on('Valider', 'form.form', function(form) {
var $form = $(form);
$.ajax({
url:"/path_to_my_html_file/BC_form2.html",
type: "POST",
success: function(form) {
alert("Form is saved");
}
});
});
</script>
Could you help me ?
Thank you
You can try to adopt by your purpose this code:
$('#form').submit(function(e) { // Prevents form to be submitted by default post request with page reloading e.preventDefault(); if (confirm("Click OK to continue?")) { // Here you can call your AJAX request callAjax($('input[type=text]').val()) } }); function callAjax(value) { // Making AJAX request to your endpoint // GET ipify just for example $.ajax({ url:"https://api.ipify.org?format=json", type: "GET", success: function(form) { alert("Form is saved"); } }); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="form"> <input type="hidden" value="MOCK FOR CSRF TOKEN" /> <br></br> <input type="text" required /> <br></br> <button type="submit">Valider</button> </form>
Use .valid() in submit function
$('#form').submit(function() {
var isValid=$("#form").valid();
if (isValid) { //If there is no validation error
var c = confirm("Click OK to continue?");
if(c){
$.ajax({
url:"/path_to_my_html_file/BC_form2.html",
type: "POST",
success: function(form) {
alert("Form is saved");
}
});
}
}
else {
alert('form is not valid');
}
});
</script>
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.