Smitty
Smitty

Reputation: 165

Flask: why isn't AJAX being called when form is submitted?

I'm making a web application with flask that takes a submitted value from a form and, sends it to a python function, and returns the response to html.

main.py:

app = Flask(__name__)


@app.route('/')
def index():
    return render_template("index.html")


@app.route('/', methods=['POST'])
def search_form():
    print(request.form)
    x = request.form['searchinput']

    a = Vbulletin(x)

    #a.reg_ver()

    def result_gen():
        return a.reg_ver()
    result_gen()

    temp = []

    for s in result_gen():
        text = s
        print(text)

I want to use ajax to send the form to flask. I know I can just use html to handle the form, but i want to figure out how to do it with ajax.

index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>UserFind Home</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <link rel="stylesheet" href="{{ url_for('static', filename='main.css') }}">
        <script type="text/javascript" src="{{ url_for('static', filename='search.js') }}"></script>
    </head>
    <body>
        <nav>
            <ul id="navlist">
                <h1>Userfind</h1>
                <li><a class="btn" href="#home">Home</a></li>
                <li><a class="btn" href="#contact">Contact</a></li>
                <li><a class="btn" href="#about">About</a></li>
                <form name=searchbar>
                    <ul id="navsearch">
                        <li class="search">
                            <input type="text" id="searchinput" name="searchinput" placeholder="Search for User here. Must be atleast 5 characters long.">
                        </li>
                        <li><button type="submit" class="btn-default">Submit</button></li>
                    </ul>
                </form>
            </ul>
        </nav>

        <p>{{ text }}</p>

        <div class="footer">
            <p>&copy;2019 Userfind</p>
          </div>
    </body>
</html>

I know I can just add the method like:

            <form method="POST" name=searchbar>

But im trying to learn how to do it with jquery/ajax.

search.js:

$(document).ready(function() {

$('form').on('submit', function(event) {

event.preventDefault();

    $.ajax({
        data : {
            x : $('#searchinput').val(),
        console.log(x)
        },
        type : 'POST',
        url : '/'
    .done(function(data) {


        if (data.error) {
            $('#errorAlert').text(data.error).show();
            $('#successAlert').hide();
        }
        else {
            $('#successAlert').text(data.x).show();
            $('#errorAlert').hide();
        }

    });


});
});

I've tried several different ways but ajax is never call. When i inspect the html no ajax is present on the form either. It just sends a get request. So how can fix this so AJAX is called when I submit the form?

Upvotes: 1

Views: 512

Answers (2)

Smitty
Smitty

Reputation: 165

I had my code set up to click form instead of button.

I changed:

$('form').on('click', function(event)

to this:

 $("#submit").click(function(e)

In flask I also had to change:

x = request.form['searchinput']

to:

x = request.form['id']

because that was what data was being passed to flask as.

In the end js looked like this:

    $(document).ready(function(){
   $("#submit").click(function(e){
        e.preventDefault();
        $.ajax({type: "POST",
            url: "/",
            data: { id: $("#searchinput").val()},
            success:function(){
                alert("POST was sent.");
            }
        })
  });
});

Upvotes: 1

ankitkanojia
ankitkanojia

Reputation: 3122

$('form').on('click', function(event) {
  event.preventDefault();
  $.ajax({
    data: {
      x: $('#searchinput').val()
    },
    type: 'POST',
    url: '/',
    success: function() {
      if (data.error) {
        $('#errorAlert').text(data.error).show();
        $('#successAlert').hide();
      } else {
        $('#successAlert').text(data.x).show();
        $('#errorAlert').hide();
      }
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <title>UserFind Home</title>

  <link rel="stylesheet" href="{{ url_for('static', filename='main.css') }}">
  <script type="text/javascript" src="{{ url_for('static', filename='search.js') }}"></script>
</head>

<body>
  <nav>
    <ul id="navlist">
      <h1>Userfind</h1>
      <li><a class="btn" href="#home">Home</a></li>
      <li><a class="btn" href="#contact">Contact</a></li>
      <li><a class="btn" href="#about">About</a></li>
      <form method="POST" name="searchbar">
        <ul id="navsearch">
          <li class="search">
            <input type="text" id="searchinput" name="searchinput" placeholder="Search for User here. Must be atleast 5 characters long.">
          </li>
          <li><button type="button" class="btn-default">Submit</button></li>
        </ul>
      </form>
    </ul>
  </nav>

  <p>{{ text }}</p>

  <div class="footer">
    <p>&copy;2019 Userfind</p>
  </div>
</body>

</html>

Upvotes: 1

Related Questions