I created a form that submits its input to a database via a PHP page, and it works great, except for that I can't get the below script to work.
The intention is to submit the form but without actually jumping to createaccount.php. However, when I use the jQuery script below it prevents the form data from being submitted at all. This code is from a project from a few years ago, and back then it worked fine. It seems it also works for everyone else on StackOverflow, so... confusing.
If it helps, I'm using Chrome. And I also tried using e instead of event, and instead of preventDefault() I also tried stopPropagation() and stopImmediatePropagation(), but these have the same results. Any ideas would be appreciated. Thanks for your time!
HTML
<form action="createaccount.php" method="post" id="form">
Username:<input type="text" name="username">
Password:<input type="password" name="password">
Email:<input type="email" name="email">
<input type="submit" name="submit" value="Submit">
</form>
JavaScript (jQuery)
$(document).ready(function() {
$("#form").on('submit', function(event){
event.preventDefault();
});
})
CodePudding user response:
after event.preventDefault() add the following:
let form = document.getElementById('form')
form.submit()
and your form will be submitted
CodePudding user response:
event.preventDefault();
Stops the form from submitting.
after that line you could do an $.ajax
request
$(document).ready(function() {
$("#form").on('submit', function(event){
event.preventDefault();
$.ajax({
url: 'createaccount.php',
type: 'post',
data: $("form").serialize(),
success: function(data) {// do something if you want to give feedback}
})
});
})