-1

I have a footer that contains a form on every page. I don't want the user to be redirected to a page when submitting the form. Instead, onclick button leads the user to a change in text in the footer on the same page. However, whenever the user inputs his email, and presses "enter" on the keyboard instead of the button, the page is immediately redirected to a "Method Not Allowed

The method is not allowed for the requested URL."

 <form action="" method="POST">
                 <div id="theDiv" class="col-xl-auto col-md-6 col-12 pt-4 my-sm-0 order-6 ">
                <div class="form-group"><label for="email" class="mb-3"><b>Subscribe to our Mailing list</b></label><input type="email" name="email" class="form-control form-control-lg" placeholder="Enter email" id="email"></div><button type="button" class="buttonsqred btn btn-primary btn-lg btn-block my-2 Subscribe mt-4 mb-3" onclick="document.getElementById('theDiv').textContent = 'You Successfully Subscribed!'; document.getElementById('theDiv').style.color = 'red'" >Subscribe</button>
            </div>
            </form>

@app.route('/subscribers', methods=['POST', 'GET'])
def subscribers():
    title = "Subscribers"

    if request.method == "POST":
        subscriber_email = request.form['email']
        new_subscriber = Subscribers(email=subscriber_email)

# Push to DB

        try:
            db.session.add(new_subscriber)
            db.session.commit()
            return redirect('/subscribers')

        except:
            return "There was an error adding your Subscription"
    else:
         return render_template("subscribers.html")
ByteMe
  • 9
  • 1

1 Answers1

0

The action attribute on your HTML <form> tag is empty, that is why it does not work.

The action attribute should be /subscribers or {{ url_for('subscribers') }} if you want to use Jinja.

The type attribute of your <button> is button instead of submit, so clicking the button does not send the form.

Examples:

<form action="/subscribers" method="POST"> ... </form>

<!-- Jinja Example -->

<form action="{{ url_for('subscribers') }}" method="POST"> ... </form>

If you want to send the form without redirection, this question is already answered here (pure JavaScript solution): https://stackoverflow.com/a/54964425/11297557

vremes
  • 654
  • 2
  • 7
  • 10