How do I pull data from JSON URL? - json

I am trying to display the "students" data in a table with their SRN, firstName, surName and allocated group. I am also trying to display their tutorial group from the "groups" data based on students SRN.
This is my HTML file:
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<title>Student groups</title>
<link rel="stylesheet" type="text/css" href="app.css">
<script type="text/javascript" src="displayStudents.js"></script>
<script type="text/javascript">
var studentsListJSON ;
function getStudentsJSON() {
makeRequest('http://homepages.herts.ac.uk/~comqgrs/ads/moduleGroups.php?moduleCode=6com9051');
}
function makeRequest(url) {
console.log("Making Request to..." + url);
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
console.log('Giving up. Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = processContents;
httpRequest.open('GET', url);
httpRequest.send();
}
function processContents() {
console.log("Call back to process contence: state = " + httpRequest.readyState + "; status = " + httpRequest.status);
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
console.log("request returned, processing data... \n" + httpRequest.responseText);
studentsListJSON = JSON.parse(httpRequest.responseText);
displayStudents();
} else {
console.log('There was a problem with the request.');
}
}
}
</script>
</head>
<body>
<h1>Student Groups for 6COM9051: More Web Scripting</h1>
<h2>Selected Students</h2>
<p>Lets go ... display the Students!</p>
<div id="studentsList"></div>
</body>
</html>
This is my JS file:
function displayStudents() {
var studentsListHTML = '<table id="studentsTable"><thead><tr><th>SRN</th><th>Firstname</th><th>Lastname</th><th>Allocated Group</th></tr></thead>'
for (var studentsName = '"students"' in studentsListJSON) {
var students = studentsListJSON[studentsName];
var studentHTML = '<tr><td>' + students.SRN + '</td><td>' + students.firstName + '</td><td>' + students.lastName + '</td><td>' + students.allocatedGroup + '</td></tr>';
studentsListHTML += studentHTML;
}
studentsListHTML += '</table>';
document.getElementById('studentsList').innerHTML=studentsListHTML;
}
I need to have the data in a table as the user opens the page on a browser and have a search bar so that the user can search for any of the data displayed in the table.

Try changing the displayStudents() method to :
function displayStudents() {
var studentsListHTML = '<table id="studentsTable"><thead><tr><th>SRN</th><th>Firstname</th><th>Lastname</th><th>Allocated Group</th></tr></thead>'
for (var studentSRN in studentsListJSON.students) {
var student = studentsListJSON.students[studentSRN];
var studentHTML = '<tr><td>' + studentSRN + '</td><td>' + student.firstName + '</td><td>' + student.lastName + '</td><td>' + student.allocatedGroup + '</td></tr>';
studentsListHTML += studentHTML;
}
studentsListHTML += '</table>';
document.getElementById('studentsList').innerHTML=studentsListHTML;
}
Note the line (line 5) - var student = studentsListJSON.students[studentSRN];
You need to use the studenSRN as a key to access the corresponding Student in the studentsListJSON.students dictionary.

Related

Need Rally HTML to return url instead of string for attachment

I'm using custom html for a rally app to query and return a list of objects with their attachments. Works well for what I'm doing, but although on screen in Rally I can click the name and it's a link to the attachment, when I grab the list and paste it into excel I end up with just the name of the attachment and I really need a link to the attachment.
Can anyone help me with this html so that it returns the actual url in Rally rather than the name with the url behind it? See these imagesenter image description here. The top represents the current results whereas the bottom represents the desired results.
<html>
<head>
<title>Story Table</title>
<meta name="Name" content="Stories with Attachments" />
<meta name="Version" content="2014.2" />
<meta name="Vendor" content="Rally Software" />
<script type="text/javascript" src="https://rally1.rallydev.com/apps/1.32/sdk.js"></script>
<script type="text/javascript">
var table = null;
function tableExample() {
var rallyDataSource = new rally.sdk.data.RallyDataSource('__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__');
function itemQuery() {
var queryObject = {
key: 'theItems',
type: iType,
fetch: 'FormattedID,Name,State,ScheduleState,Description,Attachments,ObjectID',
query: Qvalue
};
rallyDataSource.findAll(queryObject, populateTable);
}
function populateTable(results) {
if (table) {
table.destroy();
}
var col3 = 'ScheduleState';
if (iType == 'task') {
col3 = 'State';
}
var tableDiv = document.getElementById('aDiv');
var config = { 'columnKeys' : ['FormattedID', 'Name', col3, 'Attachments'],
'columnHeaders' : ['FormattedID', 'Name', col3, 'Attachments'],
'columnWidths' : ['100px', '400px', '85px', '300px']
};
table = new rally.sdk.ui.Table(config);
table.addRows(results.theItems);
for (i=0;i<results.theItems.length;i++) {
myStory = results.theItems[i];
myStoryURL = rally.sdk.util.Context.getServerInfo().getUrl()+"/#/" + '__PROJECT_OID__' + "/detail/"+ iType + "/"+myStory.ObjectID;
myStoryHTML = "<div><a href='" + myStoryURL + "' target='_top'> " +
myStory.FormattedID + "</a></div>";
myAttachments = results.theItems[i].Attachments;
myAttachmentHTML = "";
for (j=0;j<myAttachments.length;j++) {
myAttachmentOID = myAttachments[j].ObjectID;
myAttachmentName = myAttachments[j].Name;
myAttachmentURL = rally.sdk.util.Context.getServerInfo().getSlmUrl()+"/attachment/"+
myAttachmentOID + "/" + myAttachmentName;
myAttachmentHTML += "<div><a href='" + myAttachmentURL + "'>" +
myAttachmentName + "</a></div>";
}
table.setCell(i, 3, myAttachmentHTML);
table.setCell(i, 0, myStoryHTML);
}
table.display(tableDiv);
};
itemQuery();
}
rally.addOnLoad(tableExample);
</script>
<script type="text/javascript">
var Qvalue = '';
function textBoxChanged(tb, args) {
Qvalue = args.value;
}
function Qbox() {
var config = {
label : 'Query String: ',
value : '',
width: 500,
showLabel: true
};
var textBox = new rally.sdk.ui.basic.TextBox(config);
textBox.display("textbox", textBoxChanged);
}
rally.addOnLoad(Qbox);
</script>
<script type="text/javascript">
var iType = 'hierarchicalrequirement';
function typeSelect() {
function onChanged(c, args) {
iType = args.value;
}
var config = {
radios: [{label:"Stories", value:"hierarchicalrequirement"},{label:"Defects",value:"defect"},{label:"Tasks",value:"task"},{label:"Test Cases",value:"testcase"}],
labelPosition: "after",
rememberChecked: false,
defaultValue: "hierarchicalrequirement",
groupName: "itemTypes"
};
var radioButtonGroup = new rally.sdk.ui.basic.RadioButtonGroup(config);
radioButtonGroup.display("itemGroup", onChanged);
}
rally.addOnLoad(typeSelect);
</script>
</head>
<body>
<p><div id="itemGroup"></div><span id="textbox"></span>
<button onclick="tableExample()">Refresh</button>
Query Help
<br></p>
<div id="aDiv" style="overflow-y: auto;"></div>
</body>
</html>
I'm assuming you still want to be able to click on the attachment links within the app.
So try replacing this line of code:
myAttachmentHTML += "<div><a href='" + myAttachmentURL + "'>" + myAttachmentName + "</a></div>";
With this:
myAttachmentHTML += "<div><a href='" + myAttachmentURL + "'>" + myAttachmentURL + "</a></div>";

How can I display a profile stored in a database after a SQL query in a Google Spreadsheet Sidebar?

Basically here is what I'm doing:
Storing a person profile in a MYSQL Database
Creating a google spreadsheet add-on with a sidebar
giving to the user the possibility to search profiles through the DB in the add-on
giving to the user the possibility to display the datas of the profile in the Sidebar in the add-on
So Imagine you want to search John but the input you've entered in the searchbar is the letter J. The result of this query will be Jack , Johnatan, Jules, Joe and John as they all have a J. All this names will appear as link for you to click on in order to have more datas displayed (age, picture, fullname, description...). Only problem is that the only way I've managed to achieve is by making a SQL query after each keyup in my HTML input then create X numbers (in this case 5) of hidden classes with the infos, that I can show by clicking on a created link.
So this can easily work for 5 results, but imagine there's 100 of them and you only want to see one of them. Sounds crazy to create 100 hidden divs with all the infos to finally show only one.
here is an example code
code.gs
function onOpen(e) {
SpreadsheetApp.getUi().createAddonMenu()
.addItem('Start', 'showSidebar')
.addToUi();
}
function onInstall(e) {
onOpen(e);
}
function showSidebar() {
var ui = HtmlService.createHtmlOutputFromFile('UI_HTML');
SpreadsheetApp.getUi().showSidebar(ui);
}
//My function to search for profiles (returns an array with each lines found)
function searchProfile(entry){
var address = 'sql3.freemysqlhosting.net';
var user = 'user';
var userPwd = 'password';
var db = 'sql12345678910';
var instanceUrl = 'jdbc:mysql://' + address;
var dbUrl = instanceUrl + '/' + db;
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var stmt = conn.createStatement();
var ret = [];
var res = stmt.executeQuery('SELECT * FROM item WHERE name = "' + entry + '"'
+ ' OR fullname LIKE CONCAT("%", "' + entry + '", "%")'
+ ' OR description LIKE CONCAT("%", "' + entry + '", "%")');
var numCol = res.getMetaData().getColumnCount();
var i = 0;
var j = 0;
while (res.next())
{
j = 0;
if (!ret[i])
ret[i] = [];
while (j < numCol)
{
ret[i][j]= res.getString(j + 1);
j++;
}
i++;
}
return (ret);
}
UI_HTML.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.show {
display: block;
}
.hide {
display: none;
}
</style>
</head>
<body>
<div>
<p>Search Profile</p>
<input type="text" id="searchProfile" onkeyup="searchProfileHTML()" placeholder="Search for ...">
<div id="results" ></div>
</div>
<script>
function searchProfileHTML()
{
var x = document.getElementById("searchProfile").value;
google.script.run
.withSuccessHandler(createLinks)
.searchProfile(x);
function createLinks(result)
{
$('.links').remove();
if (!x)
return (0);
$('#results').append('<ul></ul>');
$('#results ul').addClass('links');
result.forEach(function(el){
//My Link to show/hide my Div
$('.links').append('<li><a id="' + el[0] + '-link" href="#">' + el[0] + '</a><div id="' + el[0] + '" class ="hide" ></div></li>');
//My div with all the infos (hidden by default)
$('#' + el[0]).append(""
+ '<img src="' + el[14] + '" height="100" width="100">'
+ "<div>"
+ "<ul>"
+ "<li>Name: "+ el[0] + "</li>"
+ "<li>Full name: "+ el[1] + "</li>"
+ "<li>Description : "+ el[2] + "</li>"
+ "<li>email: "+ el[3] + "</li>"
+ "</ul>"
+ "</div>");
$('#' + el[0] + '-link').on("click", function(){
$('#' + el[0]).toggleClass("hide show");
})
});
}
}
</script>
Anyone has an idea how I can make this more lite?

How to hide certain columns? - Google Spreadsheet

On a published (as a Web Page) Google spreadsheet:
I would not like anyone seeing four columns of a spreadsheet with sensitive data. I want these four columns just for personal use.
Solutions using IMPORTRANGE function are not suitable as a solution. That's because I create a new spreadsheet every month, with a lot of data in it, and I simply copy the four columns onto the new sheet every month. These columns also perform some calculations from the data on the same sheet.
I tried hiding columns, this way. But it is a bit uncomfortable for me.
PS. This is not the same question as this one
Well since they don't need to edit anything that makes it a lot easier.
Here's the code for displaying a table on a webapp. You can choose to make it editable or not and you can leave any columns off that you wish.
var SSID='';
var sheetName='';
function onOpen()
{
SpreadsheetApp.getUi().createMenu('HTML Spreadsheet')
.addItem('Run Spreadsheet in Dialog', 'htmlSpreadsheet')
.addToUi();
}
function htmlSpreadsheet(mode,edit){
var mode=mode||'dialog';
var edit=edit||true;
var br='<br />';
var s='';
var hdrRows=1;
var ss=SpreadsheetApp.openById(SSID);
var sht=ss.getSheetByName(sheetName);
var rng=sht.getDataRange();
var rngA=rng.getValues();
;
switch(edit){
case true:
s+='<table>'
for(var i=0;i<rngA.length;i++){
s+='<tr>';
for(var j=0;j<rngA[i].length;j++){
if(i<hdrRows){
s+='<th id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}else{
s+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
}
s+='</tr>';
}
s+='</table>';
break;
case false:
s+='<table style="border: 1px solid black;">'
for(var i=0;i<rngA.length;i++){
s+='<tr>';
for(var j=0;j<rngA[i].length;j++){
if(i<hdrRows){
s+='<th style="border: 1px solid black;">' + rngA[i][j] + '</th>';
}else{
s+='<td style="border: 1px solid black;">' + rngA[i][j] + '</th>';
}
}
s+='</tr>';
}
s+='</table>';
break;
}
//s+='<div id="success"></div>';
s+='</body></html>';
switch (mode){
case 'dialog':
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
userInterface.append(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Spreadsheet Data for ' + ss.getName() + ' Sheet: ' + sht.getName());
break;
case 'web':
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
return userInterface.append(s).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
}
function updateSpreadsheet(i,j,value)
{
var ss=SpreadsheetApp.openById(SSID);
var sht=ss.getSheetByName(sheetName);
var rng=sht.getDataRange();
var rngA=rng.getValues();
rngA[i][j]=value;
rng.setValues(rngA);
var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
return data;
}
function doGet()
{
var output=htmlSpreadsheet('web');
return output;
}
Here's the htmlss.html page:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
});
function updateSS(i,j)
{
var str='#txt' + String(i) + String(j);
var value=$(str).val();
$(str).css('background-color','#ffff00');
google.script.run
.withSuccessHandler(successHandler)
.updateSpreadsheet(i,j,value)
}
function successHandler(data)
{
$('#success').text(data.message);
$('#txt' + data.ridx + data.cidx).css('background-color','#ffffff');
}
console.log('My Code');
</script>
<style>
th{text-align:left}
</style>
</head>
<body>
<div id="success"></div>

Trying to simply implement the google+ sign in button HTML

I am trying to implement a google+ sign in button into my website! Working with HTML, and I am not sure why the button itself is not working. I am following these instructions:
https://developers.google.com/+/web/signin/add-button
This is what I have so far (I originally found code for a log in and log out button, but decided to just use the google+ API)
Where would I put this code in??
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}
Am I missing an onclicklistener or something?? Thank you!!!
<!DOCTYPE html>
<html>
<head>
<script src="https://apis.google.com/js/client:platform.js" async defer></script>
</head>
<body>
<!---<input type="button" value="Login" onclick="login()" />
<input type="button" value="Logout" onclick="logout()" />--->
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-clientid="805034040388-erokn7fetmrl9id1romu3o75m7tbnpqp.apps.googleusercontent.com"
data-cookiepolicy="single_host_origin"
data-requestvisibleactions="http://schema.org/AddAction"
data-scope="https://www.googleapis.com/auth/plus.login">
</span>
</span>
<div id="profile"></div>
<script type="text/javascript">
function logout()
{
gapi.auth.signOut();
location.reload();
}
function login()
{
var myParams = {
'clientid' : 'PUTYOUR_CLIENT_ID.apps.googleusercontent.com',
'cookiepolicy' : 'single_host_origin',
'callback' : 'loginCallback',
'approvalprompt':'force',
'scope' : 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read'
};
gapi.auth.signIn(myParams);
}
function loginCallback(result)
{
if(result['status']['signed_in'])
{
var request = gapi.client.plus.people.get(
{
'userId': 'me'
});
request.execute(function (resp)
{
var email = '';
if(resp['emails'])
{
for(i = 0; i < resp['emails'].length; i++)
{
if(resp['emails'][i]['type'] == 'account')
{
email = resp['emails'][i]['value'];
}
}
}
var str = "Name:" + resp['displayName'] + "<br>";
str += "Image:" + resp['image']['url'] + "<br>";
str += "<img src='" + resp['image']['url'] + "' /><br>";
str += "URL:" + resp['url'] + "<br>";
str += "Email:" + email + "<br>";
document.getElementById("profile").innerHTML = str;
});
}
}
function onLoadCallback()
{
gapi.client.setApiKey('PUT_YOUR_KEY');
gapi.client.load('plus', 'v1',function(){});
}
</script>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client.js?onload=onLoadCallback';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
</body>
</html>
I made it work in my localhost.
Please be sure that you followed the proper steps from that link.
Especially the first step .
After finishing the first step, you have to pay attention to two big details:
Whatever Production URL you add there, those ones will be available for your button. If you have a hosting, add that, otherwise I hope you can run your code with a localhost server (wamp, xampp etc).
Client ID
Now, this a piece of code working if you run on the specific Production URL for your Client ID (be careful to add the proper client ID in the code below)
<html>
<head>
<title>Google+ Sign-in button demo</title>
<style type="text/css">
html, body { margin: 0; padding:0;}
#signin-button {
padding: 5px;
}
#oauth2-results pre { margin: 0; padding:0;}
.hide { display: none;}
.show { display: block;}
</style>
<script type="text/javascript">
var loginFinished = function(authResult) {
if (authResult) {
var el = document.getElementById('oauth2-results');
var label = '';
toggleDiv('oauth2-results');
if (authResult['status']['signed_in']) {
label = 'User granted access:';
gapi.auth.setToken(authResult);
} else {
label = 'Access denied: ' + authResult['error'];
}
el.innerHTML =
label + '<pre class="prettyprint"><code>' +
// JSON.stringify doesn't work in IE8.
'{<br />' +
' "id_token" : "' + authResult['id_token'] +'",<br />' +
' "access_token" : "' + authResult['access_token'] + '",<br />' +
' "state" : "' + authResult['state'] + '",<br />' +
' "expires_in" : "' + authResult['expires_in'] + '",<br />' +
' "error" : "' + authResult['error'] + '",<br />' +
' "error_description" : "' + authResult['error_description'] + '",<br />' +
' "authUser" : "' + authResult['authuser'] + '",<br />' +
' "status" : {"' + '<br />' +
' "google_logged_in" : "' + authResult['status']['google_logged_in'] + '",<br />' +
' "method" : "' + authResult['status']['method'] + '",<br />' +
' "signed_in" : "' + authResult['status']['signed_in'] + '"<br />' +
' }<br />' +
'}</code></pre>';
toggleDiv('signin-button');
} else {
document.getElementById('oauth2-results').innerHTML =
'Empty authResult';
}
};
function toggleDiv(id) {
var div = document.getElementById(id);
if (div.getAttribute('class') == 'hide') {
div.setAttribute('class', 'show');
} else {
div.setAttribute('class', 'hide');
}
}
</script>
<script src="https://plus.google.com/js/client:platform.js" type="text/javascript"></script>
</head>
<body>
<div id="signin-button" class="show">
<div class="g-signin" data-callback="loginFinished"
data-approvalprompt="force"
data-clientid="CLIENT_ID"
data-requestvisibleactions="http://schema.org/CommentAction"
data-cookiepolicy="single_host_origin"
>
</div>
</div>
</body>
</html>
The error in the console I see is:
Callback function named "signinCallback" not found
You did not use the function from here: data-callback="signinCallback"
In your documentation it is down there:
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}

Sort JSON data by Date/Time value

Hope someone could help with this small task. I have an array of text blocks that have a DateTime value assigned to them. I would like to publish those text blocks sorted by DateTime so that the latest updated item is always on top.
Here is the script:
function jsonCallBack(data) {
var strRows = "";
$.each(data.News, function(i, item) {
var htmlNewsBody = item["htmlNewsBody"];
var maxLength = 120
var trimmedString = htmlNewsBody.substr(0, maxLength);
trimmedString = trimmedString.substr( 0, Math.min( trimmedString.length,
trimmedString.lastIndexOf(" ") ) );
strRows += "<div id='nrNewsItem-" + i + "'>";
strRows += "<h3>" + item["txtTitle"] + "</h3>";
strRows += "<p>" + item["dtDateTime"] + "</p>";
strRows += "<p>" + trimmedString + "...</p>";
strRows += "</div>"
});
$("#printHere").html(strRows);
};
Also have a working jsFiddle with JSON data.
You can add a custom compare method:
function compare(a,b) {
if (a.dtDateTime < b.dtDateTime) {
return 1;
}
if (a.dtDateTime > b.dtDateTime) {
return -1;
}
return 0;
}
Then in your function:
function jsonCallBack(data) {
data.News.sort(compare);
....