Home > Software design >  How to stay in the same page after submiting form without disabling the action (HTML/Flask)
How to stay in the same page after submiting form without disabling the action (HTML/Flask)

Time:12-08

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  action="{{ url_for('send_email') }}">
        <div >
            <label for="to-address">To </label>
            <input id= "to-address" name="to-address" type="email" 
            placeholder="[email protected]" >
       </div>
       <div >
             <label for="title">Title</label>
             <input id= "email-title" name="email-title" type="text" placeholder="Title" 
             >
       </div>
       <div >
            <label for="message">Message</label>
            <textarea id= "email-body" name="email-body" placeholder="Send Message" ></textarea>
       </div>

       <button id="email-send-btn" type ="submit" > 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="[email protected]",
            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;
    });
 });

CodePudding user response:

Historically returning false from a submit handler prevented form submission without needing to call submit event object methods such as preventDefault and/or stopPropagation

With careful reading you may be able to infer that jQuery documentation says the same thing:

If you'd like to prevent forms from being submitted unless a flag variable is set ... [return the value of the flag from the submit handler added using the jQuery .submit(handler) syntax]

means that if the flag variable is set true, form submission is not prevented.

Hence return false instead of true to stay on the page, letting jQuery handle cross browser compatibility issues.

CodePudding user response:

You can use render template flash message.

https://flask.palletsprojects.com/en/2.2.x/tutorial/templates/

https://flask.palletsprojects.com/en/2.2.x/patterns/flashing/

from flask import render_template, flash

... your code here ...

flash('Email has been sent successfully.')
return render_template('yourtemplate.html')

And in your template you have to put this code, like in documentation:

% with messages = get_flashed_messages() %}
  {% if messages %}
    <ul class=flashes>
    {% for message in messages %}
      <li>{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}

Of course you can use any HTML tag instead of unordered list with items.

CodePudding user response:

Right now you just use another callback that does something when the form submits but you don't block the standard submitting. In order to achieve that you should managed the event defining that he should "prevent default" actions.

$form.submit(function(e){ //< add here "e" parameter
       e.preventDefault(); //< add this
       $.post($(this).attr('action'), $(this).serialize(), function(response){
             // do something here on success
       },'json');
       return false; //< change this
    });
  • Related