I wrote an HTML template to send an email using Flask. In the HTML script, I have a form that has a "send" button and once it's clicked, it triggers an email in Flask.
HTML Script
<form class="form-container" action="{{ url_for('send_email') }}">
<div class="form-group">
<label for="to-address">To </label>
<input id= "to-address" name="to-address" type="email"
placeholder="sample@email.com" class="form-input">
</div>
<div class="form-group">
<label for="title">Title</label>
<input id= "email-title" name="email-title" type="text" placeholder="Title"
class="form-input">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea id= "email-body" name="email-body" placeholder="Send Message" class="form-
text-area"></textarea>
</div>
<button id="email-send-btn" type ="submit" class="btn btn-primary"> Send </button>
</form>
FLASK
@application.route('/send_email')
def send_email():
to_address = request.args.get('to-address')
subject = request.args.get('email-title')
text = request.args.get('email-body')
msg= Message(
subject,
sender="abc@email.com",
recipients=to_address,
)
msg.html = render_template("email.html", text=text)
mail.send(msg)
return("success")
The email itself is working well but I have an issue with redirecting the page after clicking the "Send" button. Once I click on the Send button, whose id="email-send-btn", I want to stay in the current page, probably showing a notification popup to indicate the email has been sent successfully. I put return('success
)` in the last line of my Flask script, because I had to return something to avoid a blank page.
I tried this following to stay in the same page after hitting the Send button. It allows me to stay in the same page, but also blocks the action completely and doesn't send any email. Is there any way to stay in the same page after clicking the send button without blocking the action of sending email?
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return true;
});
});