function getUsername()
{
var userName = document.form.screen_name.value;
document.getElementById("display").innerHTML = userName;
var apiName = "https://api.twitter.com/1/users/lookup.json?screen_name=" + userName + "&callback=?";
document.getElementById("display2").innerHTML = apiName;
$(document).ready(function(){
$.getJSON(apiName, function(twitter) {
alert(twitter.name);
$('#showdata').html("<p>item1="+twitter.follwers_count+" item2="+twitter.friends_count+"</p>");
});
});
Javascript code.
<form method="get" action="#" name="form">
Username: <input type="text" name="screen_name" id="username"/>
<input type="submit" value="submit" onclick="getUsername()" />
</form>
<p>Your username is <h2 id="display"></h2></p>
<p>Your api url is <h2 id="display2"></h2></p>
HTML Code
Whats wrong with this code? The alert comes back undefined.
Thanks
The data comes back as an array. You need to get the object at index 0:
function getUsername()
{
var userName = document.form.screen_name.value;
document.getElementById("display").innerHTML = userName;
var apiName = "https://api.twitter.com/1/users/lookup.json?screen_name=" + userName + "&callback=?";
document.getElementById("display2").innerHTML = apiName;
$(document).ready(function(){
$.getJSON(apiName, function(twitter) {
alert(twitter[0].name);
$('#showdata').html("<p>item1=" + twitter[0].follwers_count + " item2=" + twitter[0].friends_count + "</p>");
});
});
}
Of course, you could always just write twitter = twitter[0]; at the start of your function.
Oh, and here's your code jQuery-ified:
function getUsername()
{
var userName = $('[name=screen_name]').val();
$("#display").html(userName);
var apiName = "https://api.twitter.com/1/users/lookup.json?screen_name=" + userName + "&callback=?";
$("#display2").html(apiName);
$(document).ready(function(){
$.getJSON(apiName, function(twitter) {
alert(twitter[0].name);
$('#showdata').html("<p>item1=" + twitter[0].follwers_count + " item2=" + twitter[0].friends_count + "</p>");
});
});
}
Related
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>";
hi on my website i've a comment box,
everytime i post a comment it get posted below the last comment
my question is: how do i place new comments on top of the old ones.
website: kru.run
This is my full code right now,
<textarea id="title1" type="text " rows="1" cols="15" onkeyup="Allow()" placeholder="username"></textarea>
<textarea id="title" type="text " rows="3" cols="125" onkeyup="Allow()" placeholder="write a comment..."></textarea>
<input type="submit" value="Send" onclick="insert()" style="width:50px;" /></form>
</div>
<div id="display"></div>
<script type="text/javascript">
var titles = [];
var titleInput = document.getElementById("title");
var titleInput1 = document.getElementById("title1");
var messageBox = document.getElementById("display");
function Allow() {
if (!user.title.value.match(/[a-zA-Z]$/) && user.title.value != "") {
user.title.value = "";
alert("Please Enter only alphabets");
}
window.location.reload()
}
function insert() {
titles.push(titleInput1.value + ": " + titleInput.value);
clearAndShow();
}
function clearAndShow() {
titleInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += " " + titles.join("<br/> ") + "<br/>";
}
</script>
</div>
</div>
</div>
<br><br>
specifically
i think the insert function is the problem
what can i use instead of push?
function insert () {
titles.push(titleInput1.value + ": " + titleInput.value);
clearAndShow();
}
try:
function insert () {
titles.unshift(titleInput1.value + ": " + titleInput.value);
clearAndShow();
}
to insert as first item.
I am having an issue when trying to submit a form with user information that inserts into a table. I have a userForm that allows user data to be entered with the following:
<form id="userForm">
<fieldset>
<legend>Add User</legend>
<p>First Name: <input id="fname" type="text" name="fname"/></p>
<p>Last Name: <input id="lname" type="text" name="lname"/></p>
<p>Email: <input id="email" type="text" name="email"/></p>
<p>Password: <input id="password" type="text" name="password"/></p>
</fieldset>
<input id="addUser" type="submit" name="add" value="Add User" onclick="addRow()" />
</form>
<script src="script.js"></script>
This then launches the following code in my script.js code:
function addRow(){
var form = document.getElementById("userForm");
var req = new XMLHttpRequest();
// Add the form data to the ajax request
var queryString = "";
var fname = form.fname.value;
var lname = form.lname.value;
var email = form.email.value;
var password = form.password.value;
queryString += "fname=" + fname + "&";
queryString += "lname=" + lname + "&";
queryString += "email=" + email + "&";
queryString += "password=" + password;
req.open('GET', '/insert-user?' + queryString, true);
req.send();
console.log(req.status);
Which executes the server side code:
app.get('/add-user', function(req,res){
var context = {};
res.render('addUser', context);
});
app.get('/insert-user',function(req,res,next){
var context = {};
pool.query("INSERT INTO user (`fname`, `lname`, `email`, `password`) VALUES (?,?,?,?)",
[req.query.fname, req.query.lname, req.query.email, req.query.password],
function(err, result){
if(err){
next(err);
return;
}
context.results = "Inserted id " + result.insertId;
res.render('exerciseTable',context);
});
});
The record is not being inserted into the table. When I console.log(req.status) I see 0 in the console. The add-user page is the form that the user fills out and then the insert-user code is called but it does not seem to be working. In fact, the URL does not change from http://18.219.103.143:3000/add-user to http://18.219.103.143:3000/insert-user? when I submit. It just stays static. It seems like my app.get('/insert-user'... code isn't even being called. Does anyone know what I am missing?
I am getting this error in the console:
Try to put
<form id="userForm" onsubmit="return false;">
Otherwise the default action on your form will be called. As your button is a submit button and that your default action is not set so it defaults to the same page and returning nothing or true will reload your page.
A have a JavaScript that handles localisation.
That gives me a
Position: <input type="text" id="Position1" name="Position1" value="">
This works, and i get the current position on the webpage.
Now, I want to have that position in a form and give it to my SQL by a php script. The php works.
I hva tried:
<input type="hidden" name="poss" id="Position1">
and I know this does not work.
But how do I do it? How do I convert from id= to name= ??
Script:
<script>
window.onload = function(){
var x = document.getElementById('Position1');
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.value = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.value = "" + position.coords.latitude + "," + position.coords.longitude;
}
getLocation();
};
</script>
Position: <input type="text" id="Position1" name="Position1" value="">
<input type="hidden" name="poss" id="Position1">
<input type="submit" style="height:40px;width:350px" />
</form>
try with document.getElementsByName('poss')[0].value = "" + position.coords.latitude + "," + position.coords.longitude; it should work
I'm working on an Angular Application in which the main page (where the angular module is initialize) has a header where I want to show different divs if the user is logged or not.
Here is the header code fragment of the index.html:
<header ng-controller="HeaderController">
<div class="container">
<div class="row">
<div class="col-lg-12 col-xs-12">
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 none">
<a class="navbar-brand" href="#page-top"><img src="Content/img/logo.png" class="img-responsive" alt="logo"></a>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-4 col-lg-offset-6 col-md-offset-6 col-sm-offset-9" ng-if="showloginheader">
<!--ng-if="showloginheader"-->
<span href="#" class="button-login" id="toggle-login" ng-click="OnLoginClick()">Ingresar</span><img src="Content/img/logo.png" id="logo_min" alt="logo">
<div id="login" ng-controller="LoginController">
<form name="loginForm" ng-submit="login()" role="form">
<input type="text" placeholder="Ingresá el usuario" required ng-model="username" />
<input type="password" placeholder="Ingresá la contraseña" required ng-model="password" />
<!--<input type="submit" class="login" value="Ingresar" />-->
<input type="checkbox" id="checkbox" checked><div class="reco-contra">Recordar contraseña</div>
<div class="olvi-contra"><a>Olvidaste la contraseña?</a></div>
<!--<div class="form-actions">-->
<input type="submit" class="login" value="Ingresar" /> <!-- ng-disabled="form.$invalid || vm.dataLoading" -->
<input type="submit" id="clase-fb" value="Ingresar con Facebook" />
<input type="submit" id="clase-tw" value="Ingresar con Twitter" />
<input type="submit" id="clase-goo" value="Ingresar con Google" />
<div class="olvi-contra"><a>Olvidaste la contraseña?</a></div>
</form>
<input type="submit" value="¡Registrate ahora!" />
</div>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-4 col-lg-offset-6 col-md-offset-6 col-sm-offset-9" ng-if="showcurrentuserheader"><!--ng-if="showcurrentuserheader"-->
<span href="#" class="log-img" id="toggle-login"><img src="img/fefe.png" alt="logo">Pablo</span>
<div id="login">
<div id="login-ok">
<div class="opcion-log">
<strong>RECETAS OBTENIDAS</strong>
</div>
<div class="opcion-log">
<i class="fa fa-cog fa-spin"></i> PERFIL
</div>
<div class="opcion-log">
CERRAR SESION
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</header>
You can notice that there are two divs below the logo, what I want to achieve is to show the first div (the one that has a "ng-if=showloginheader") meanwhile the user isn't logged in and then show the other one when the user gets into the application (has a "ng-if=showcurrentuserheader").
I would like to know which would be the best option to do this, until now I have tried to do it with the ng-if directive.
First I initialize the variables throw a service (to make it accesible by several controllers):
(function () {
'use strict';
angular
.module('iziCooker')
.factory('UserService', UserService);
UserService.$inject = ['$http'];
function UserService($http) {
var service = {};
var showloginheader = true;
var showcurrentuserheader = false;
service.GetLoginHeaderState = GetLoginHeaderState;
service.GetCurrentUserHeaderState = GetCurrentUserHeaderState;
service.ChangeHeadersVisibility = ChangeHeadersVisibility;
return service;
function GetLoginHeaderState() {
return showloginheader;
}
function GetCurrentUserHeaderState() {
return showcurrentuserheader;
}
function ChangeHeadersVisibility() {
showloginheader = false;
showcurrentuserheader = true;
}
}
})();
Then I assign those values in the HeaderController:
(function () {
'use strict';
angular
.module('iziCooker')
.controller('HeaderController', HeaderController);
HeaderController.$inject = ['$scope', 'UserService'];
function HeaderController($scope, UserService) {
$scope.showloginheader = UserService.GetLoginHeaderState();
$scope.showcurrentuserheader = UserService.GetCurrentUserHeaderState();
}
})();
Up to this point, this works properly because the HeaderController is injected when the application starts (it's in the "master page" of Angular, index.html).
But then I tried to change the variables values in the login controller after you got a successful response from the DB to get into the application.
(function () {
'use strict';
angular
.module('iziCooker')
.controller('LoginController', LoginController);
LoginController.$inject = ['$location', 'AuthenticationService', 'FlashService', '$scope', 'UserService'];
function LoginController($location, AuthenticationService, FlashService, $scope, UserService) {
$scope.dataLoading = false;
$scope.username = "";
$scope.password = "";
console.log("Login Controller Loaded!");
//vm.login = login;
(function initController() {
// reset login status
AuthenticationService.ClearCredentials();
})();
$scope.login = function login() {
$scope.dataLoading = true;
AuthenticationService.Login($scope.username, $scope.password, function (response) {
if (response.success) {
AuthenticationService.SetCredentials($scope.username, $scope.username);
UserService.ChangeHeadersVisibility();
$location.path('/map');
} else {
FlashService.Error(response.message);
$scope.dataLoading = false;
}
});
};
}
})();
When I am redirected to the "/map" view, it still shows the first div. It seems that those ng-if variables aren't updated or something like that. Perhaps I'm missing something.
I'm almost sure that this isn't the way to do this, so I would to know if I must change something or change completely the code.
Thank you.
Edit:
Authentication Service
(function () {
'use strict';
angular
.module('iziCooker')
.factory('AuthenticationService', AuthenticationService);
AuthenticationService.$inject = ['$http', '$cookieStore', '$rootScope', '$timeout', 'UserService'];
function AuthenticationService($http, $cookieStore, $rootScope, $timeout, UserService) {
var service = {};
service.Login = Login;
service.SetCredentials = SetCredentials;
service.ClearCredentials = ClearCredentials;
return service;
function Login(username, password, callback) {
/* Dummy authentication for testing, uses $timeout to simulate api call
----------------------------------------------*/
//$timeout(function () {
// var response;
// UserService.GetByUsername(username)
// .then(function (user) {
// if (user !== null && user.password === password) {
// response = { success: true };
// } else {
// response = { success: false, message: 'Username or password is incorrect' };
// }
// callback(response);
// });
//}, 1000);
/* Use this for real authentication
----------------------------------------------*/
$http.post('ws/api/Usuario/Login', { username: username, password: password })
.success(function (response) {
callback(response);
});
}
function SetCredentials(username, password) {
var authdata = Base64.encode(username + ':' + password);
$rootScope.globals = {
currentUser: {
username: username,
authdata: authdata
}
};
$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; // jshint ignore:line
$cookieStore.put('globals', $rootScope.globals);
}
function ClearCredentials() {
$rootScope.globals = {};
$cookieStore.remove('globals');
$http.defaults.headers.common.Authorization = 'Basic';
}
}
// Base64 encoding service used by AuthenticationService
var Base64 = {
keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
encode: function (input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
do {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this.keyStr.charAt(enc1) +
this.keyStr.charAt(enc2) +
this.keyStr.charAt(enc3) +
this.keyStr.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
},
decode: function (input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) {
window.alert("There were invalid base64 characters in the input text.\n" +
"Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
"Expect errors in decoding.");
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do {
enc1 = this.keyStr.indexOf(input.charAt(i++));
enc2 = this.keyStr.indexOf(input.charAt(i++));
enc3 = this.keyStr.indexOf(input.charAt(i++));
enc4 = this.keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
}
};
})();
The best way to implement something like this would be to set/unset a user object in your AuthenticationService. Then you can set a scope variable like $scope.authentication and make ng-if (or ng-show) dependent on the user object.
Since it looks like you are setting up a user model in $rootScope you can use it anywhere.
$rootScope.globals = {
currentUser: {
username: username,
authdata: authdata
}
};
So in your markup you will have this for the not logged in header:
<div ... ng-hide="$root.globals.currentUser">
And for the logged in header:
<div ... ng-show="$root.globals.currentUser">
You can also try ng-show and ng-hide:
HTML
<h1 ng-show="toggleHeader">First header</h1>
<h1 ng-hide="toggleHeader">Second header</h1>
JavaScript
$scope.toggleHeader = true; //false to switch header.
Although the problem is elsewhere. Try writing {{showloginheader}} in your HTML to see if it really does change between true/false.