passing Flask list to HTML - javascript

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)

Related

Trying to pass javascript arrays to Python Flask

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

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

Dojo - request.post on button click - syntax error

Three questions:
1) Is there any way to make this code more neater? Mainly to avoid so much nesting and quotes within quotes issues?
2) Any advice on parsing error below. I tested some code separately to mke sure it works. (see second code box below).
3) I'm getting "undefined" when I look at request.body in the NodeJS server program that handles this request. From what I read, I didn't need a body parser if the content-type was set to application/json.
<button id="updateStudentButton" data-dojo-type="dijit/form/Button"
data-dojo-props="iconClass:'dijitIconTask',
onClick:function(){
var url = '../student/' + dom.byId('studentId').value;
var studId = dojo.byId('studentId').value;
dom.byId('studentFeedback').value +=
'updateStudentButton clicked studentID=' + studId + '\n';
var firstname = dom.byId('studentFirstname').value;
var lastname = dom.byId('studentLastname').value;
var postBody = JSON.parse(
'{ \"data\": {' +
' \"firstname\": "' + firstname + '\",' +
' \"lastname\": "'+ lastname + '\"' +
'},' +
'\"headers\": { ' +
' \"Content-Type\": \"application/json\" ' +
'}}'
);
dom.byId('studentFeedback').value += 'postBody=' + postBody + '\n';
require(['dojo/request'], function(request){
// AJAX Post the data to the server
request.post(url, postBody
).then(function(response){
dom.byId('studentFeedback').value += response + '\n';
// parse and return data in text boxes
var respJSON = JSON.parse(response);
var rowsAffected = respJSON.rowsAffected;
dom.byId('studentFeedback').value += 'rowsAffected=' + rowsAffected + '\n';
},
function(error){
dom.byId('studentFeedback').value += response;
});
})
}
">
Update
</button>
I tested separatley in NodeJS to make sure quotes all work and saw the correct console.log:
var firstname = 'John';
var lastname = 'Doe';
var postBody = JSON.parse(
'{ \"data\": {' +
' \"firstname\": "' + firstname + '\",' +
' \"lastname\": "'+ lastname + '\"' +
'},' +
'\"headers\": { ' +
' \"Content-Type\": \"application/json\" ' +
'}}'
);
console.log ("postBody=");
console.dir (postBody);
Getting parsing error:
dojo/parser::parse() error Error: SyntaxError: Invalid or unexpected token in data-dojo-props='iconClass:'dijitIconTask',
onClick:function(){
var url = '../student/' + dom.byId('studentId').value;
var firstname = dom.byId('studentFirstname').value;
var lastname = dom.byId('studentLastname').value;
var postBody = JSON.parse(
'{ \'
at Object.construct (parser.js.uncompressed.js:401)
at Object.<anonymous> (parser.js.uncompressed.js:190)
at Object.map (dojo.js:8)
at Object._instantiate (parser.js.uncompressed.js:184)
at parser.js.uncompressed.js:893
at _2f8 (dojo.js:8)
at Promise.then._305.then (dojo.js:8)
at Object.parse (parser.js.uncompressed.js:890)
at Object._parse (html.js.uncompressed.js:301)
at Object.onEnd (html.js.uncompressed
The way to avoid quotes within quotes issue is to have your onClick javascript code inside <script></script> tags.
Below a modified version of your code that works Ok in my environment. The request activates the error callback as I don't have the server handling side.
See the documentation here for the declarative details (use of data-dojo-event), and here for the request details.
For the request, I have stringified the data, as this is what I do in my application (php on the server side). The documentation says it can be a string or object, you may want to try sending the data object, depending on what your server environment expects.
Rgds,
jc
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Neal Walters stask overflow test</title>
<link rel="stylesheet" href="dojo-release-1.12.2-src/dijit/themes/claro/claro.css" media="screen">
</head>
<body class="claro">
<button type="button" id="updateStudentButton" data-dojo-type="dijit/form/Button" data-dojo-props="iconClass:'dijitIconTask'">
<span>update</span>
<script type='dojo/on' data-dojo-event='click'>
var dom = require('dojo/dom');
var url = '../student/' + dom.byId('studentId').value;
var studId = dom.byId('studentId').value;
dom.byId('studentFeedback').value += 'updateStudentButton clicked studentID=' + studId + '\n';
var firstname = dom.byId('studentFirstname').value;
var lastname = dom.byId('studentLastname').value;
var data = {firstname: firstname, lastname: lastname};
//dom.byId('studentFeedback').value += 'postBody=' + postBody + '\n';
require(['dojo/request'], function(request){
// AJAX Post the data to the server
request.post(url, {data: JSON.stringify(data), method: 'POST', handleAs: 'json'}).then(
function(response){
dom.byId('studentFeedback').value += JSON.stringify(response) + '\n';
// parse and return data in text boxes
var rowsAffected = response.rowsAffected;
dom.byId('studentFeedback').value += 'rowsAffected=' + rowsAffected + '\n';
},
function(error){
dom.byId('studentFeedback').value += error;
}
);
});
</script>
</button><p>
<form>
Student feedback: <input id="studentFeedback"><p>
Student first name: <input id="studentFirstname"><p>
Student last name: <input id="studentLastname"><p>
Student id: <input id="studentId"><p>
</form>
<script src="dojo-release-1.12.2-src/dojo/dojo.js" data-dojo-config="async:true"></script>
<script type="text/javascript">
require(["dojo/parser", "dijit/form/Button", "dojo/domReady!"],
function(parser){
parser.parse();
});
</script>
</body>
</html>
data-dojo-props="iconClass:'dijitIconTask'
don't you need to end with "?
data-dojo-props="iconClass:'dijitIconTask'"
You can better the way you are creating JSON ex:
var json={};
json.name="Test";
json.age="23"
when you print json (JSON.stringify(json)), you will see
{
"name":"Test",
"age":"23"
}

Unable to receive parameter in query string when redirected to other page

Hi I am developing one application in java-script. I have two pages default.aspx and addnewitem.aspx. there is one html table in default.aspx and one button. When i click on button i want to redirect to addnewitem.aspx page. I have some parameters to send in query string. I am able to redirect to addnewitem.aspx but page not found error i am getting. I am not sure why i am getting page not found error. I am trying as below.
function getValues() {
var Title = "dfd";
var PrimarySkills = "fdfd";
var SecondarySkills = "dfdf";
var url = "http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=" + encodeURIComponent($(Title)) + "&PrimarySkills=" + encodeURIComponent($(PrimarySkills)) + "&SecondarySkills=" + encodeURIComponent($(SecondarySkills));
window.location.href = url;
}
I am checking querystring in addnewitem.aspx as below.
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["Title"] != null && queryString["PrimarySkills"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Title:</b> " + queryString["Title"] + " <b>PrimarySkills:</b> " + queryString["PrimarySkills"] + " <b>SecondarySkills:</b> " + queryString["SecondarySkills"];
$("#lblData").html(data);
alert(data);
}
});
</script>
"http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=%5Bobject%20Object%5D&PrimarySkills=%5Bobject%20Object%5D&SecondarySkills=%5Bobject%20Object%5D"
I tried lot to fix this. May i know where i am doing wrong? Thanks for your help.
You should use the relative path in your url instead of hard coding the entire folder structure, which is probably incorrect since you are getting a 404. And you need to change the url every time you publish the site to the hosting enviroment when you hard code it like that.
So change
var url = "http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=...
into
var url = "/AddNewItem.aspx?Title=...
if both the pages are in the same folder. Should AddNewItem.aspx be located in the Pages folder, you have to add that folder of course: var url = "/Pages/AddNewItem.aspx?Title=...

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