0

Sorry if the title is a little confusing. A kind user here on StackOverflow helped me make my Flask app display some scraped data, only now I have added a parameter in the function so that I can scrape the data I want to search for. I have an input box, and I want to be able to get the data from it, and pass it as a string in my python function in Flask

Current HTML Side

<!DOCTYPE html>
<html lang = "en">
<head>
    <meta charset = "utf-8">

    <title>NBA Data Web App</title>
</head>

<body>
    <script src = "http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" crossorigin = "anonymous"></script>
    <form id = "nameForm" method = "POST" role = "form">
        <input name = "text">
        <button id = "searchBtn"> Search </button>
    </form>

    <div id = "container"></div>

    <script type = "text/javascript">
        //Function to take place when our search button is clicked
        $('button#searchBtn').click(function() {
            $.ajax({
                url: '/_get_data',
                data: $('form').serialize(),
                type: 'POST',
                success: function(response) {
                    console.log = response;
                },
                error: function() {
                    alert('Failure in first Ajax call');
                }
            });

            /*Everything below this was working before, as I only made one ajax call when a button was pressed. Now, when I press the button, I want to pass its contents as a string to my scrape_data() function in Flask, and return, and display, its contents as shown below. */




            //Declare our list so we can print something, and loop through it later
            var data_list;
            //Variable for our HTML table
            var rowMax = 29, html = "<table><tr>";
            //Post request
            $.post('/_get_data', {
                //If done, do this
            }).done(function(response) {
                /* Assign our scraped data to our variable that was declared earlier, 
                which is turned into an array here in JS */
                data_list = response['data'];
                //Declare some variables for making our table
                var perRow = 1, count = 0, table = document.createElement("table"),
                row = table.insertRow();
                //Loop through the data and add it to the cells
                for (var i of data_list) {
                    //Insert a cell for each piece of data
                    var cell = row.insertCell();
                    //Add the data to the cell
                    cell.innerHTML = i;
                    //Increment our count variable
                    count++;
                    //If we have met our set number of items in the row
                    if (count % perRow == 0) {
                        //Start a new row
                        row = table.insertRow();
                    }
                }
                //Add the table to our container in our HTML
                document.getElementById("container").appendChild(table);
                //If request fails
            }).fail(function() {
                alert("request failed");
            });
        });
    </script>

</body>
</html>

Python (Flask) Side

rom flask import Flask, render_template, jsonify, request, escape, url_for

#Get our lists to post
headers = data_headers()

#Start the flask app
app = Flask(__name__)

#Start page
@app.route('/')
def index():
    return render_template('index.html')

#What happens when our button is clicked
@app.route('/_get_data', methods = ['POST'])
def _get_data():
    text = request.form['text']

    #Here, I am trying to assign the contents of the input box of the form to a variable, so I can pass that variable as a parameter for my function.
    data = scrape_data(text)
    #Return the json format of the data we scraped
    return jsonify({'data' : data})

#Run the app
if __name__ == "__main__":
    app.run(debug = True)

I am currently getting error 405 method not allowed. I'm not sure if my syntax in the first Ajax call is incorrect, or if I need to break this up into two different @app.route(urls) since each call is going a different way.

Robert Smith
  • 673
  • 10
  • 25
  • I wrote an answer in which I explained how to send data to FLASK via ajax and jquery. [You can take inspiration from that](https://stackoverflow.com/questions/52870184/get-data-from-html-and-do-some-operation-on-it-and-pass-the-data-back-to-the-f/52883461#52883461). Do not hesitate to come back to me in case of trouble. – Tobin Nov 02 '19 at 10:50
  • @Tobin do i need to have this split into two calls? Or can i leave it like it is above – Robert Smith Nov 02 '19 at 11:47
  • As you will have noticed there are two parts in the request. the first sends the data to Flask. flask performs its operations based on this data and returns the result via Ajax. and here you can retrieve this data and display it on your page. So technically you do not need to separate these operations in your code. – Tobin Nov 02 '19 at 12:53
  • @Tobin yes I did note that. I’m currently at work right now and I’m not sure we’re in the same time zone, but I will give it a shot in about 8 hours. Thank your for your help – Robert Smith Nov 02 '19 at 12:56
  • @Tobin I have tried following your tutorial and did get somewhere, however, I am now getting a 404 error, as explained in my latest StackOverflow post – Robert Smith Nov 03 '19 at 01:04
  • You'll have to show the version of the code you're currently using to see what's causing the problem – Tobin Nov 03 '19 at 14:53
  • @Tobin I fixed it in my latest post, and answered my own question. Thank you though! – Robert Smith Nov 03 '19 at 15:10

1 Answers1

0

If you use the method attribute of form element and do not specify the action, request will be sent /. What is happening here is when you click on search button it will send two post requests one to '/' and '/_get_data' from ajax. In Flask routing if you do not explicitly provides methods=[] that route will allow GET only. Remove the method attribute from you form, you should not get method not allowed error.

Srikanth Chekuri
  • 1,944
  • 1
  • 9
  • 19