2

I am trying to pass some javascript arrays to Flask to set my templates page but all I get in the out put page is "In the Host text box, you entered: None" message, here is my code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <script src="static/script.js"></script>
        <title>Comms Checker</title>
        </head>
        <body>
    <form name="ResultPage" action = "passFails.html" onsubmit="return validateTestPage()" method="post">
         Number of Hosts/Ports:<br><input type="text" id="Number"><br/><br/>
        <a href="#" id="filldetails" onclick="addFields()">Enter Comms Details</a>
        <div id="container"/>
    </form>
    </body>
</html>

the code above calls the javascript function below:

function addFields(){
            // Number of inputs to create
            var number = document.getElementById("Number").value;

            // Container <div> where dynamic content will be placed
            var container = document.getElementById("container");

            // Clear previous contents of the container
            while (container.hasChildNodes()) {
                container.removeChild(container.lastChild);
            }

            for (var i=1;i<=number;i++){
                container.appendChild(document.createTextNode("Host: " + i));
                var host = document.createElement("input");
                host.type = "text";
                host.id = "Host " + i;
                container.appendChild(host);

                container.appendChild(document.createTextNode("Port: " + i));
                var port = document.createElement("input");
                port.type = "text";
                port.id = "Port " + i;
                container.appendChild(port);

                // Append a line break
                container.appendChild(document.createElement("br"));
                container.appendChild(document.createElement("br"));
}
    var button = document.createElement("input");
    button.setAttribute("type", "button");
    button.setAttribute('value', 'Check');
    button.setAttribute('onclick', 'checkVal()');
    container.appendChild(button);

    return true;
}



function checkVal() {
    var myHost=[];
    var myPort=[];
// Number of inputs to create
    var number = document.getElementById("Number").value;

    for (var i = 1; i <= number; i++) {

        //pass myHost and myPort to first.py for further processing.

         myHost.push(document.getElementById('Host ' + i).value);
         myPort.push(document.getElementById('Port ' + i).value);

        /*alert("Value of Host: " + i + " is: " + myHost[i]);
        alert("Value of Port: " + i + " is: " + myPort[i]);*/
    }

    for (var i=0; i<number; i++){

        alert("Value of Host: " + i + " is: " + myHost[i]);
        alert("Value of Port: " + i + " is: " + myPort[i]);
    }

    $.get(
        url="/passFails",
        data={host: myHost},
        success = function (data) {
            alert('page content: ' + data);
        }
    );
return true
}

the javascript code should pass the array/list "myHost" to Python, but for some reason it fails to do so with no error messages. the python script is as follows

from flask import Flask, render_template, request
import json
import jsonify

app = Flask(__name__)


@app.route('/Results')
def Results():

    return render_template('Results.html')


@app.route('/passFails')
def passFails():
    data = request.args.get('host')
    print("The Value in passFails is :%s " % data)
    return render_template('/passFails.html', Value=data)


if __name__=='__main__':
    app.run(debug=True)

and finally, the above python script should pass the data to the last HTML page passFails.html where all the values in the array/list gets printed. the passFails page is as follows

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>In the Host text box, you entered: {{Value}}</h1>

</body>
</html>

I just want to know why the code in javascript part is not able to pass the list to python OR if there is anything wrong in the Python script which is causing problem in receiving the array? Any Help will be greatly appreciated.

Sharan Arumugam
  • 353
  • 6
  • 12
Ali
  • 175
  • 1
  • 2
  • 7

4 Answers4

0

If you add a debug printing as a first line in a passFails, you'd see something like that:

def passFails():
    print(request.args)
    # Out: ImmutableMultiDict([('host[]', '1'), ('host[]', '2'), ('host[]', '3')])

As you've said, you've trying to pass some javascript arrays, so your requests looks something like:

$.get(
    url="/passFails",
    data={host: [1,2,3]},
    success = function (data) {
        alert('page content: ' + data);
    }
);

And it'll be converted (what you can and totally should see in your browser debug console) to a request-url like:

http://localhost/passFails?host[]=1&host[]=2&host[]=3

So, your value couldn't be found at a host key. To make it work you could use request.args.getlist('host[]'). Another option is to serialize the myHost value from array to a JSON string before sending a request, so you'd be able to access value as request.args.get['host'], but you'll have to deserialize it from a JSON representation in Flask.

Fine
  • 2,114
  • 1
  • 12
  • 18
  • I tried using request.args.getlist('host') and request.args.getlist('host[]'), the output is still empty brackets "[]". I am not sure how serialize and de-serialize work..... – Ali Feb 20 '19 at 19:50
  • I notices something in javascript where it say:$.get( url="/passFails", data={host: myHost}, success = function (data) { alert('page content: ' + data); } ); the $ in the beginning is showing as "Unresolved variable or type $" when you hover over your mouse on it. – Ali Feb 21 '19 at 00:19
0

Change .get to .getlist

request.args.getlist('host')

examples

Peace

Community
  • 1
  • 1
Sharan Arumugam
  • 353
  • 6
  • 12
  • 1
    I tried using request.args.getlist('host'), but the out put is still a pair of empty brackets "[]", not sure what else I can do..... – Ali Feb 20 '19 at 19:46
  • Oh. hmm. You can give [this answer](https://stackoverflow.com/a/2602127/2496613) a try then. – Sharan Arumugam Feb 21 '19 at 08:05
0

Finally, I found the answer, all I had to do was to include the following script tag in my HTML file for the javascript to to user the $.get() function to send data to python. that was the problem and it is successfully solved:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Thanks to all of you guys for sharing your responses.

Ali
  • 175
  • 1
  • 2
  • 7
-1

In python file, you need to add methods = ['POST'], so your app route should be:@app.route('/passFails', methods = ['POST']), and then you can check if request.method == 'POST': #write you code

Jay85
  • 116
  • 2
  • 10
  • I found the source of the problem, but not sure how to fix. So here is what I got when I inspect the elements of the page: ReferenceError: $ is not defined script.js:116:3 checkVal http://127.0.0.1:5000/static/script.js:116 onclick http://127.0.0.1:5000/Results#:1 instead of the the list "myHost" which I expected. So the source of the problem is in the JAVASCRIPT part of the code where I am trying to send the list to Python(Flask) where I got the $ not defined error, causing it to fail to send data to python and therefore an empty pair of brackets instead of a list. Any Ideas – Ali Feb 22 '19 at 03:11