0

I'm working on a project for a class and I have starter code that I am editing. they way its supposed to work is that when the user creates a venue it goes to the home page with a message saying venue x has been listed. Once I add the post request in the new_venue.html it does nothing after I click the submit button nothing happens, but I know its doing something because the app.py prints the name that signed up.

Below is Code from the new_venue.html.

I added the script section and the post request

    {% extends 'layouts/main.html' %}
{% block title %}New Venue{% endblock %}
{% block content %}
  <div class="form-wrapper">
    <form id="venueInfo" method="post" class="form">
      <h3 class="form-heading">List a new venue <a href="{{ url_for('index') }}" title="Back to homepage"><i class="fa fa-home pull-right"></i></a></h3>
      <div  class="form-group">
        <label for="name">Name</label>
        {{ form.name(id='name', class_ = 'form-control', autofocus = true) }}
      </div>
      <div class="form-group">
          <label>City & State</label>
          <div class="form-inline">
            <div id='city' class="form-group">
              {{ form.city(class_ = 'form-control', placeholder='City', autofocus = true) }}
            </div>
            <div id='state' class="form-group">
              {{ form.state(class_ = 'form-control', placeholder='State', autofocus = true) }}
            </div>
          </div>
      </div>
      <div id='address' class="form-group">
        <label for="address">Address</label>
        {{ form.address(class_ = 'form-control', autofocus = true) }}
      </div>
      <div id='phone_num' class="form-group">
          <label for="phone">Phone</label>
          {{ form.phone(class_ = 'form-control', placeholder='xxx-xxx-xxxx', autofocus = true) }}
        </div>
      <div id="genres" class="form-group">
        <label for="genres">Genres</label>
        <small>Ctrl+Click to select multiple</small>
        {{ form.genres(class_ = 'form-control', autofocus = true) }}
      </div>
      <div id="fb_link" class="form-group">
          <label for="genres">Facebook Link</label>
          {{ form.facebook_link(class_ = 'form-control', placeholder='http://', autofocus = true) }}
        </div>
      <input type="submit" value="Create Venue" class="btn btn-primary btn-lg btn-block">
    </form>

    <script type="text/javascript">

      document.getElementById("venueInfo").onsubmit=function(e){
        e.preventDefault();
        fetch('/venues/create',{
        method:'POST',
        body:JSON.stringify({
          'name': document.getElementById('name').value,
          'city': document.getElementById('city').value,
          'state': document.getElementById('state').value,
          'address': document.getElementById('address').value,
          'phone_num': document.getElementById('phone_num').value,
          'genres': document.getElementById('genres').value,
          'fb_link': document.getElementById('fb_link').value,
      }),
        headers: {'Content-type': 'application/json'}
      })
      .then(function(){
      })
    }

    </script>


  </div>

{% endblock %}

below is the code from app.py

    @app.route('/venues/create', methods=['GET'])
def create_venue_form():
  form = VenueForm()
  return render_template('forms/new_venue.html', form=form)

@app.route('/venues/create', methods=['POST'])
def create_venue_submission():
  name = request.get_json()['name']
  print(name)

  flash('Venue ' + request.form['name'] + ' was successfully listed!')

  return render_template('pages/home.html')
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153

2 Answers2

1

flash messages work with redirection, refer to https://flask.palletsprojects.com/en/1.1.x/patterns/flashing/#simple-flashing

so instead rendering the template, return redirection object to the home page:

@app.route('/venues/create', methods=['POST'])
def create_venue_submission():
  # name = request.get_json()['name']
  name = request.values.get('name')

  print(name)

  flash('Venue ' + request.form['name'] + ' was successfully listed!')

  #  return render_template('pages/home.html')
  return redirect(url_for('home'))  # -- HERE --

Update

i think you are doing things the wrong way, you don't need the javascript to submit the form data via ajax post since ajax is used to update the page without reloading it (btw you didn't put any logic in .then(function(){}) callback to show up the message), but after submitting the form you want to redirect the user to the home page with a flash message so the ajax approach you are using is the wrong approach, just remove or comment the javascript code block and add the action to the form

<form id="venueInfo" method="post" action="{{ url_for('create_venue_submission') }}" class="form">

...

and in your function create_venue_submission() you should change

name = request.get_json()['name']

to

name = request.values.get('name')

# other fields
name = request.values.get('name')
city = request.values.get('city')
state = request.values.get('state')
address = request.values.get('address')
phone_num = request.values.get('phone_num')
genres = request.values.get('genres')
fb_link = request.values.get('fb_link')

see this wiki https://stackoverflow.com/a/16664376/12368419

cizario
  • 3,995
  • 3
  • 13
  • 27
  • Still the same issue, I did return redirect(url_for('index')) and the page still doesnt show up. – MightyPaladin Dec 29 '20 at 13:45
  • This is a project for class with most of this being starter code ( i added the javascript) we need to pull the form data so I can add it to a database so thats why I pulled the data using AJAX, am I wrong in this? the strange thing is when I click submit I get this on my terminal 127.0.0.1 - - [29/Dec/2020 09:13:43] "POST /venues/create HTTP/1.1" 302 - 127.0.0.1 - - [29/Dec/2020 09:13:43] "GET / HTTP/1.1" 200 - which tells me it went thru but not rendering for some reason. – MightyPaladin Dec 29 '20 at 14:39
  • also, when I do remove the javascript I added it works fine but the problem is I cant pull the data as I am doing now. – MightyPaladin Dec 29 '20 at 14:41
  • 1
    Thank you, this pointed me in the right direction. I ended up using name=request.form.get('name') – MightyPaladin Dec 29 '20 at 17:48
0

If you are submitting your form via ajax, you will need to redirect in the success portion of the ajax call. Also, keep in mind that flash will not work via ajax. You will need to use the standard form post.

$.ajax({
    'url': 'post_url',
    success: function(msg){
       //read the msg here and determine if success or not then redirect
    }
})

This will not work when doing an ajax form post:

return redirect(url_for('index'))

If you use the standard (pseudo code) without posting via ajax, it will redirect:

<form method=post action=route>
    <input type=submit>
</form>
CodeLikeBeaker
  • 20,682
  • 14
  • 79
  • 108