I am creating a Flask application using html, css, flask and vanilla javascript as well as ajax.
I have 0 experience using Javascript and all the code I have written is from around the internet trying to piece together things.
I am creating a contact form where after the contact form is subitted I want the main contact form to dissapear and display a message:
The code itself works like it sends and email creates a new commit to the database but the whole page now does not refresh at all and wont display the 2nd div. shown bellow. The issues I am having is this. If I use instead of a the form requirments work but it does the refresh but if i use a button the form requirments dont work and but it does not refresh the page.
I am not so good at posting questions here on stack so if you have questions ask
example:
<form>
<div>
<h2> main form </h2>
<button type = "submit" onclick="saveContactForm();return false">Submit</button>
</div>
<form>
<div>
<h2> show after form submit>
</div>
My js is
function saveContactForm() {
var formData = {
name: $("input[name='name']").val(),
email: $("input[name='email']").val(),
subject: $("select[name='subject']").val(),
message: $("textarea[name='message']").val(),
};
$.ajax({
url: baseUrl,
type: "POST",
contentType : "application/json",
data: JSON.stringify(formData),
success: function (response) {
autoReply(formData.email,formData.subject,formData.message)
},
error: function (error) {
alert('Email failed to send:', error);
},
});
}
function autoReply(email,subject,message) {
let parms = {
email: email,
subject: subject,
message: message
};
service_id = secret;
template_id = secret;
public_key = secret;
emailjs.send(service_id, template_id, parms, public_key).then(function(response) {
document.querySelector(".container").style.display="none";
document.querySelector(".back").style.display="flex";
},
function(error) {
console.error('Email failed to send:', error);
});
}
I am trying to have my submit button not refresh the page
3
Answers
Try to use
event.preventDefault()
at the top of the functionsaveContactForm()
. So, it means that the default action that belongs to the event will not occur.In the button type=’submit’, it always tries to submit the form at the server level and refresh the page. So, to hold this default event call, you have to pass
event.preventDefault()
at the top.Please be sure to answer the question. Provide details and share your research!
But avoid …
Asking for help, clarification, or responding to other answers.
Making stateme
Please add
event
intosaveContactForm(event);
in buttonand add event.preventDefault() into saveContactForm function