1

I am trying to pass Flask list to HTML, but for some reason the output is a blank HTML page. below are my HTML and Javascript code where I am sending list to Python:

<!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="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script src="/static/script.js"></script>
        <script type="text/javascript"></script>
        <title>Vodafone 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="javascript:void(0)" id="filldetails" onclick="addFields()">Enter Comms Details</a>
        <div id="container"/>
    </form>
    </body>
</html>

and here is the javascript code:

function validateLoginPage() {
    var x = document.forms["loginPage"]["sourcehost"].value;
    var y = document.forms["loginPage"]["username"].value;
    var z = document.forms["loginPage"]["psw"].value;
    if(x=="" ||y=="" || z==""){
         alert("Please fill empty fields");
         return false;
    }
    else{
        return true;

    }
}
function validateTestPage() {
    var a = document.forms["ResultPage"]["DestinationHost"].value;
    var b = document.forms["ResultPage"]["port"].value;
    if(a=="" ||b==""){
         alert("Please fill empty fields");
         return false;
    }
    else{
        return true;

    }
}

    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);
        }

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

            alert("Value of Host: " + (i+1) + " is: " + myHost[i]);
            alert("Value of Port: " + (i+1) + " is: " + myPort[i]);
        }
         $.get(
            url="/passFails",
            data={'host' : myHost},
            success = function () {
                console.log('Data passed successfully!');
            }
        );

        return true;
    }

and here is my Python code where I am receiving the list successfully and even iterating through the values, but the script fails to send the list to my HTML page.

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 pass_fails():

    host_list = request.args.getlist('host[]')

    print("Value of DATA variable in passFails Decorator is: %s" % host_list)

    for val in host_list:

        print("The value in VAL Variable is: %s" % val)

    return render_template('passFails.html', hosts=host_list)


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

below is the HTML that should print the list sent from python, but all I get is a blank page.

<!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="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="/static/script.js"></script>
    <script type="text/javascript"></script>
    <title>Vodafone Comms Checker</title>
</head>
<body>
<ul>
    {% for host in hosts %}

    <li>In the Host text box, you entered: {{ host }}</li>

    {% endfor %}
</ul>

</body>
</html>

Below is the output when I run the program:

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [24/Feb/2019 13:44:44] "GET /Results HTTP/1.1" 200 -
127.0.0.1 - - [24/Feb/2019 13:44:44] "GET /static/script.js HTTP/1.1" 200 -
127.0.0.1 - - [24/Feb/2019 13:44:44] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [24/Feb/2019 13:44:56] "GET /passFails?host%5B%5D=a&host%5B%5D=b&host%5B%5D=c HTTP/1.1" 200 -
Value of DATA variable in passFails Decorator is: ['a', 'b', 'c']
The value in VAL Variable is: a
The value in VAL Variable is: b
The value in VAL Variable is: c
Value of DATA variable in passFails Decorator is: []
127.0.0.1 - - [24/Feb/2019 13:45:03] "GET /passFails HTTP/1.1" 200 -

Can anyone tell me what is wrong with the code, and why I can't send my Python list to HTML?????

Ali
  • 175
  • 1
  • 2
  • 7
  • Is the HTML `document` reloaded when the `
    ` is submitted?
    – guest271314 Feb 24 '19 at 02:57
  • not sure what you want to say, but when I submit values from 1st HTML page, I open a new browser tab and navigate to the 2nd HTML page where I am supposed to get the results, all I get is a blank page. – Ali Feb 24 '19 at 03:11
  • You can send the request with query string parameters then parse the query string at opened `window`, see [Redirect a Popup and Post Message](https://stackoverflow.com/questions/54509181/redirect-a-popup-and-post-message); [How can I send form data to test.html by using asynchronous communication?](https://stackoverflow.com/questions/46461819/how-can-i-send-form-data-to-test-html-by-using-asynchronous-communication) – guest271314 Feb 24 '19 at 03:17

1 Answers1

1

In your checkVal() function, you are attempting to submit the values to your template asynchronously (via AJAX), but you're not rendering the template with that context.

I would remove this part of your checkVal() function:

$.get(
    url="/passFails",
    data={'host' : myHost},
    success = function () {
        console.log('Data passed successfully!');
    }
);

And replace it with this:

window.location.href = "/passFails?" + $.param({"host": myHost});

As @guest271314 alluded to, this sends the parameters as a query string, which can then be parsed by the template.

Update Based on Comments

If you have to submit the processed data using a "non-AJAX" POST request, the below should work. This is probably not the best way to do this, but without refactoring your entire code, it's the quickest I can think of to make your code work.

Step 1: Modify the form tag in Results.html

Change your form tag to: <form name="ResultPage" method="" action="">. In other words, remove the values for method and action.

Step 2: Modify the checkVal() function in script.js

Change your checkVal() function to look like this:

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);
    }

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

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

    $(document.body).append('<form id="hiddenForm" action="/passFails" method="POST">' +
        '<input type="hidden" name="host" value="' + myHost + '">' +
        '<input type="hidden" name="port" value="' + myPort + '">' +
        '</form>');
    $("#hiddenForm").submit();
}

This basically processes the form that the user is entering their data into, puts that data into a separate hidden form, and submits that hidden form as a POST to the server.

Step 3: Modify pass_fails() in app.py to access the data.

In your pass_fails() method, change the value of your host_list variable to be host_list = list(request.form["host"].split(",")). This will read the tuple value for "host" and convert it from a CSV string to a list.

Here's the full version of the modified method:

@app.route('/passFails', methods=["POST", "GET"])
def pass_fails():
    host_list = list(request.form["host"].split(","))
    port_list = list(request.form["port"].split(","))

    print("Value of DATA variable in passFails Decorator is: %s" % host_list)

    for val in host_list:
        print("The value in VAL Variable is: %s" % val)

    return render_template('passFails.html', hosts=host_list)
JoshG
  • 6,472
  • 2
  • 38
  • 61
  • Just want to let you know Mr. AndroidNoobie that you are an angel. I have been scratching my head for hours to figure out what is wrong with my code, but you pointed exactly to problem like a specialist doctor. God Bless you! – Ali Feb 24 '19 at 06:12
  • @IftikharAli Happy to help! Feel free to mark the answer as "accepted" so others with the same problem can find it more easily in the future. :) – JoshG Feb 24 '19 at 06:28
  • Just 1 more question, how can you send multiple lists using your code? I trued putting another pair of {} brackets and another pair of key: value pair, but I get [ ] in the output. – Ali Feb 25 '19 at 00:25
  • @IftikharAli I'm not sure if this is what you mean, but you can add multiple parameters to the same query string. For example: `window.location.href = "/passFails?" + $.param({"host": myHost, "port": myPort, "someOtherList": myOtherList});` -- is this what you mean? If so, just add the additional parameters as properties in the object passed to `$.param()` like so. – JoshG Feb 25 '19 at 03:48
  • 1
    That is exactly what I wanted, Thank you so much once again. – Ali Feb 25 '19 at 04:32
  • updates: Im trying to send my lists from javascript to python using post. I am successfully getting my lists in python, but upon clicking the "check" button, I should go to a page "passFails.html" with results, but it is not going anywhere... here is my new javascript code: $.post("/results",{"hosts" : myHost,"ports" : myPort}, function() { console.log("Data sent successfully!"); }); ----------Any Ideas????? – Ali Feb 26 '19 at 04:47
  • looks like I don't have enough reputation points to use chat, but yes I want to send the parameters (lists) through POST. In fact, I have successfully passed the parameters to my Python, but the problem is that, when I do so, it doesn't get redirected to the passFails.html page and when I try to manually enter the (http://127.0.0.1:5000/passFails), it show a blank page with no errors to know whats wrong. – Ali Feb 26 '19 at 07:38
  • I just posted an update to my answer above. I hope it helps. If you have any further questions, I would suggest posting them as a new question. :) – JoshG Feb 26 '19 at 10:28
  • 1
    Hand down, you Sir are an awesome programmer,you keep amazing me every time without any exception. Feels like you can read my mind....AWESOME. Thank you so very much. I wish I be 1/2 as good as you.. – Ali Feb 26 '19 at 11:05