Trying to pass javascript arrays to Python Flask - javascript

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/>
Enter Comms Details
<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.

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.

Change .get to .getlist
request.args.getlist('host')
examples
Peace

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.

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

Related

XMLHttpRequest fails reading XML InfoPath form due to mso-application line

I'm trying to create an ASPX page on my SharePoint site to read existing InfoPath forms. Testing locally with JavaScript and XMLHttpRequest worked fine but when the page is uploaded to SharePoint something very odd happens if the XML file has a specific line of data in it. When testing with simple XML files this line causes a problem:
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.4"?>
When present in the XML file I'm trying to read, something odd happens. Instead of getting the contents of the file I get what appears to be an HTML page from SharePoint. The page doesn't display anything and has references to InfoPath and SharePoint libraries. I have no idea where the HTML is coming from. Removing that single line from the XML file causes everything to work as expected. Running outside of SharePoint appears to work as well. I will include a sample XML file and code I used to test.
Update : If the input file extension is TXT and not XML then the problem goes away. I assume this means that SharePoint is running code when XML files are read and injecting itself into my get request.
<?xml version="1.0" encoding="utf-8"?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.4"?>
<my:myFields xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2017-05-05T14:19:13">
<my:User_Name>Joe</my:User_Name>
<my:Email_Address>joe.smith#abc.com</my:Email_Address>
</my:myFields>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="lib/jquery/jquery-3.4.1.min.js"></script>
<title></title>
<script>
var oReq = new XMLHttpRequest();
oReq.addEventListener("progress", updateProgress);
oReq.addEventListener("error", transferFailed);
oReq.addEventListener("abort", transferCanceled);
oReq.addEventListener("loadend", transferComplete);
function Test_Req_xml() {
console.log("starting test_req_xml function");
let filename = document.getElementById('inFileName').value;
console.log("file name " + filename);
oReq.addEventListener("load", transferComplete_xml);
oReq.open("GET", filename);
oReq.responseType = "document";
oReq.send();
}
var transferComplete_xml = function (response) {
console.log({ 'transferComplete xml response:': response });
console.log({ 'oReq.responseXML': oReq.responseXML });
console.log({ 'oReq.responseType': oReq.responseType });
console.log({ 'oReq.responseURL': oReq.responseURL });
console.log({ 'oReq': oReq });
parseFile(oReq.responseXML.documentElement.outerHTML);
};
// progress on transfers from the server to the client (downloads)
function updateProgress(oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total * 100;
console.log("percent " + percentComplete);
} else {
// Unable to compute progress information since the total size is unknown
console.log("loaded is " + oEvent.loaded);
}
}
function transferComplete(evt) {
console.log("The transfer is complete.");
}
function transferFailed(evt) {
console.log("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
console.log("The transfer has been canceled by the user.");
}
//this will parse XML file and output it to website
var parseFile = function (text) {
var xmlDoc = $.parseXML(text),
$xml = $(xmlDoc),
$email = $xml.find("Email_Address"),
$naming = $xml.find("User_Name");
console.log({ 'xmldoc ': xmlDoc });
var currentdate = new Date();
var datetime = currentdate.getDate() + "/" + (currentdate.getMonth() + 1) + "/" + currentdate.getFullYear() + " # " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();
$("#output").empty();
$("#output").append("<br/>");
$("#output").append("<span>Date: " + datetime + "</span><br/>");
$("#output").append("<span>Name: " + $naming.text() + "</span><br/>");
$("#output").append("<span>Email: " + $email.text() + "</span><br/>");
};
</script>
</head>
<body>
<div class="row m-sm">
<span>File name: </span><input id="inFileName" type="text" class="form-control" placeholder="" value="test_xml_file3.xml">
</div>
<div class="row m-sm">
<button id="btnTest3" class="btn btn-outline-secondary" type="button" onclick="Test_Req_xml()">Test xml </button>
</div>
<div class="row m-sm">
<ul id="output"></ul>
</div>
</body>
</html>
I am not entirely sure how it happens but my guess is SharePoint Online is intercepting the get request for files with the XML extension and when it finds the line below it attempts to run some code against the request. I don't see any issues when the file doesn't have an XML extension, nor do I see an issue when the line below is missing from an XML file. Now I need to find out if there is a way around this.
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.4"?>

passing Flask list to HTML

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/>
Enter Comms Details
<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?????
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)

how to load data using a javascript

I have almost zero experience with Javascript , I need to use this Javascript in my php script .
<script>
let arr = ["alfa", "beta", "charlie"]
const updateResult = query => {
let resultList = document.querySelector(".result");
resultList.innerHTML = "";
arr.map(algo =>{
query.split(" ").map(word =>{
if(algo.toLowerCase().indexOf(word.toLowerCase()) != -1){
resultList.innerHTML += `<li class="list-group-item">${algo}</li>`;
}
})
})
}
updateResult("")
</script>
This script load the data using
let arr =
However suppose I have all the data specified there in a file in this format
c:/data/mydata.txt
and the data.txt contains data in this form (one data per row)
alfa
bravo
charlie
Now how should I change the javascript above to load the data from c:/data/mydata.txt and not using
let arr = ["alfa", "beta", "charlie"]
?
Thank you
You do not need to change your file, but you cannot use it directly due to security issues. If I would write a Javascript which reads your secret files and you load my page, all your secrets would be revealed, therefore, if you want to load a file, you either have to allow your user to upload it and once the user uploads the file do your logic, or, you can request it via AJAX.
How to upload a file
An example for this is
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
<p id="demo"></p>
<script>
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += "<br><strong>" + (i+1) + ". file</strong><br>";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "<br>";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes <br>";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
</script>
<p><strong>Tip:</strong> Use the Control or the Shift key to select multiple files.</p>
</body>
</html>
source: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_fileupload_files
Getting the file via AJAX
In order to do that, you will need to:
send an AJAX request in your javascript code
parse the request and send back the file via PHP
do your logic in Javascript when the request is responded
Example:
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Download POST Request</title>
</head>
<body>
Enter a text and click the button: <input type="text" id="content" value="Text for the generated pdf">
<button id="download">Send AJAX Request and download file</button>
<script>
document.getElementById('download').addEventListener('click', function () {
var content = document.getElementById('content').value;
var request = new XMLHttpRequest();
request.open('POST', '../server/', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.responseType = 'blob';
request.onload = function() {
// Only handle status code 200
if(request.status === 200) {
// Try to find out the filename from the content disposition `filename` value
var disposition = request.getResponseHeader('content-disposition');
var matches = /"([^"]*)"/.exec(disposition);
var filename = (matches != null && matches[1] ? matches[1] : 'file.pdf');
// The actual download
var blob = new Blob([request.response], { type: 'application/pdf' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// some error handling should be done here...
};
request.send('content=' + content);
});
</script>
</body>
</html>
PHP
<?php
require_once 'vendor/autoload.php';
if($_SERVER['REQUEST_METHOD'] === 'POST') {
header('Content-type: application/pdf');
http_response_code(200);
// Contents
$pdfContent = !empty($_POST['content']) ? $_POST['content'] : 'no content specified';
// Generate the PDOF
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10, $pdfContent);
return $pdf->Output(null, 'foobar-' . time() . '.pdf');
}
// Bad method
http_response_code(405);
exit();
Source: https://nehalist.io/downloading-files-from-post-requests/
You will of course need to modify the code to comply to your needs. Reading a tutorial would not hurt.
you can use ajax for loading data from external file.
a sample of jquery get call is given below. You can also use the same code with your file path and variables.
$("button").click(function(){
$.get("demo_test.php", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
if you are using pure java script instead of jQuery you have to use pure ajax calls.
for more details about jQuery ajax check this link

Chrome extension : Stuck at injecting script won't execute js

I am trying to build a chrome extension. Which would do some search on the page and post the results to the extensions.
I am having a hard time running this. Whenever I try to run the extension it is just stuck on Injecting Script.
my re.js
function printDetails(document_r) {
var test = document_r.body;
var text = test.innerText;
var delim="^^ validatedCache :";
var endlim="</site>";
var idx = text.indexOf(delim);
var endInd=text.indexOf(endlim);
var tag = "accountName";
var regex = "<" + tag + ">(.*?)<\/" + tag + ">";
var regexg = new RegExp(regex,"g");
var matches = [];
while (match = regexg.exec(text.substring(idx+delim.length,endInd))) matches.push("Account Name::::::"+match[1]);
return matches;
}
chrome.extension.sendMessage({
action: "getSource",
source: "\n\n\n DETAILS>>>>>\n\n"+printDetails(document)
});
selection.js
chrome.extension.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
message.innerText = request.source;
}
});
function onWindowLoad() {
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {
file: "re.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.extension.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.extension.lastError.message;
}
});
}
window.onload = onWindowLoad;
popup.html
<!DOCTYPE html>
<html style=''>
<head>
<script src='selection.js'></script>
</head>
<body style="background-image:url(12.png);width:400px; border: 2px solid black;background-color:white;">
<div id='message'>Injecting Script....</div>
</body>
</html>
I know there is some problem with these 2 lines only.
var test = document_r.body;
var text = test.innerText;
What I wan't is to extract the webpage ( contents ) into a string which I am hopefully doing by the above two lines of code.
Then do some string manipulation on the code.If I run directly this code in a console with a dummy string . I can execute it so figure something is wrong with these two lines.
My extension is stuck on " Injecting Script..."
Some help would be appreciated.
PS:yes I was able to run it earlier with the same code but somehow it doesn't run now.

Rally javascript displays nothing, having an issue with queries

I'm trying to query based on a selected iteration, and display some results based on the stories of that iteration.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta name="Name" content="SubField Query" />
<title>SubField Query Example</title>
<script src="/apps/1.26/sdk.js"></script>
<script type="text/javascript">
function onLoad() {
rallyDataSource = new rally.sdk.data.RallyDataSource('__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__');
var iterConfig = {};
iterDropdown = new rally.sdk.ui.IterationDropdown(iterConfig, rallyDataSource);
iterDropdown.display(document.getElementById("test"), onSelected);
rallyDataSource.findAll(queryConfig, showStories);
}
function showStories(results) {
var info = document.getElementById("info");
info.innerHTML = "<b>Iteration Story Information</b><br>";
var story;
for (var i = 0; i < results.stories.length; i++){
story = results.stories[i];
info.innerHTML += story.Name + ' - ' + story.Owner + ' - ' + story.Project + ' - ' + story.State + ' - ' + story.PlanEst + '<br>';
}
};
function onSelected() {
var queryConfig = {
type: 'hierarchicalrequirement',
key: 'stories'
query: '(Iteration.Name =' + iterDropdown.getSelectedName() + ')'
fetch: 'Name, Owner, Project, State, PlanEst'
}
}
rally.addOnLoad(onLoad);
</script>
</head>
<body>
<h1>Test Report Page</h1>
<div id = "test"></div>
<div id = "info"></div>
</body>
</html>
I have some trouble understanding the flow of the program. The way I see it, onLoad runs, and in onLoad it calls the onSelected function to create a query and then uses that query in a findAll command to run said query. I have tried moving showStories around various places to see if that changed the results, but it did nothing. Please advise.
The asynchronous nature of javascript and callbacks can be a bit intimidating at first. You're really close. Here is some fixed up code:
function onLoad() {
//code snipped above
//display the iteration dropdown and call onSelected when it's ready
iterDropdown.display(document.getElementById("test"), onSelected);
}
function onSelected() {
var queryConfig = {
type: 'hierarchicalrequirement',
key: 'stories',
query: '(Iteration.Name = "' + iterDropdown.getSelectedName() + '")', //include quotes around name
fetch: 'Name,Owner,Project,State,PlanEst' //no spaces in fetch
};
//call rallyDataSource.findAll here, and showStories will be called with the data
rallyDataSource.findAll(queryConfig, showStories);
}
function showStories(results) {
//show stories here
}
//program execution starts here
rally.addOnLoad(onLoad);
So the basic flow is onLoad, onSelected, showStories.

Categories

Resources