I have looked through all the similar posts out there but nothing seems to help. This is what I have
<section>
<form id="contact-form" action="" method="post">
<fieldset>
<input id="name" name="name" placeholder="Name" type="text" />
<input id="email" name="email" placeholder="Email" type="text" />
<textarea id="comments" name="comments" placeholder="Message"></textarea>
<div class="12u">
<a href="#" id="form-button-submit " class="button" onClick="sendForm()">Send Message</a>
<a href="#" id="form-button-clear" class="button" onClick="document.getElementById('contact-form').reset()">Clear Form</a>
</div>
<ul id="response"></ul>
</fieldset>
</form>
</section>
function sendForm() {
var name = $('input#name').val();
var email = $('input#email').val();
var comments = $('textarea#comments').val();
var formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
}); // end ajax
}
What I am unable to do is prevent the page refresh when the #form-button-submit
is pressed. I tried return false;
I tried preventDefault()
and every combination including return false;
inside the onClick
. I also tried using input type="button"
and type="submit"
instead and same result. I can't solve this and it is driving be nuts. If at all possible I would rather use the hyperlink due to some design things.
I would really appreciate your help on this.
Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.
You can use event. preventDefault() to prevent the default event (click) from occurring.
If you can run javascript, which seems like you can, create a new iframe, and post to that iframe instead. You can do <form target="iframe-id" ...> That way all the redirects happen in the iframe and you still have control of the page. The other solution is to also do a post via ajax.
The form submit() Method in HTML DOM is used to send the form data to the web-server. It works as same as submit button. It does not contain any parameters. Syntax: formObject.submit()
Modify the function like this:
function sendForm(e){
e.preventDefault();
}
And as comment mentions, pass the event:
onclick = sendForm(event);
Update 2:
$('#form-button-submit').on('click', function(e){
e.preventDefault();
var name = $('input#name').val(),
email = $('input#email').val(),
comments = $('textarea#comments').val(),
formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With