hai guys i got data from restfull web service to angular function i need to place this data in the form table but i am not getting the code so pls help me my code is. I need to show in table form what i get in json pls suggest me
<script type="text/javascript">
function ContactController($scope,$http) {
// $scope.contacts = ["hi#email.com", "hello#email.com"];
$scope.add = function() {
$http.get('http://localhost:8080/ProjectManagement/REST/GetProject/Details').success(function(data, status, headers, config,response){
var json = JSON.stringify(data);
var getresponseText = JSON.parse(json);
var prjdetails=getresponseText.responseText;
var fields = getresponseText.split("|");
$scope.people = [];
var projectid = fields[0];
var projectname = fields[1];
var claintid = fields[2];
var projectstatus = fields[3];
var prjstartdate = fields[4];
var prjenddate = fields[5];
var lastmodified = fields[6];
var prjpinurl = fields[7];
claim = '';
claim = '{ "records":[{';
claim += '"projectid": "'+ projectid+ '", ';
claim += '"projectname": "'+ projectname+ '", ';
claim += '"claintid": "'+ claintid+ '", ';
claim += '"projectstatus": "'+ projectstatus + '", ';
claim += '"prjstartdate": "'+prjstartdate+ '", ';
claim += '"prjenddate": "'+ prjenddate + '", ';
claim += '"lastmodified": "'+ lastmodified + '", ';
claim += '"prjpinurl": "'+ prjpinurl + '", ';
claim += '}]}';
}).error(function(data, status, headers, config,response) {
});
}
}
</script>
If you get json returned from the server, do not call JSON.stringify since it is already "stringified" when sent from the server.
It is not possible to help you further without seeing the actual response from the server.
Related
I've got a working script that grabs the last row of a Google sheet and pushes the info into Google contacts.
var ss = SpreadsheetApp.getActiveSheet(); //var emailRow = ss.getRange('F2:F').getValues();
var emailRowNum = ss.getLastRow(); //var emailRowNum = emailRow.filter(String).length + 1;
function email() {
var emailNew = ss.getRange(emailRowNum,6).getValue(); //var emailNew = ss.getRange("F"+emailRowNum).getValues();
return emailNew;}
function givenName() {
var fname = ss.getRange(emailRowNum,4).getValue();
return fname;}
function lastName() {
var lname = ss.getRange(emailRowNum,5).getValue();
return lname;}
function loc() {
var street = ss.getRange(emailRowNum,8).getValue();
var city = ss.getRange(emailRowNum,9).getValue();
return street + " " + city;}
function phone() {
var phone = ss.getRange(emailRowNum,7).getValue();
return phone;}
function notes() {
var date = ss.getRange(emailRowNum,1).getValue();
var work = ss.getRange(emailRowNum,2).getValue();
var photo = ss.getRange(emailRowNum,3).getValue();
var site = ss.getRange(emailRowNum,12).getValue();
var find = ss.getRange(emailRowNum,10).getValue();
var referrer = ss.getRange(emailRowNum,11).getValue();
return (date + "\n\n" + work + "\n\n" + photo + "\n\n" + site + "\n\n" + find + " " + referrer + "\n\n-- eom --\n\n");}
function create() {
var fname = givenName();
var lname = lastName();
var contact = ContactsApp.createContact(fname, lname, email());
var group = ContactsApp.getContactGroup('emf');
group.addContact(contact);
var contacts = ContactsApp.getContactsByName(fname + ' ' + lname);
var setaddress = contacts[0].addAddress(ContactsApp.Field.HOME_ADDRESS,loc());
var setphone = contacts[0].addPhone(ContactsApp.Field.MAIN_PHONE,phone());
for (var i in contacts) {
contacts[i].setNotes(notes());
}
}
I'd like to modify it so that instead of grabbing the last row, it checks a column for a (not) value. If value is not found, then update Google contacts with that row's information.
Currently, I'm getting a 'Range not found' error ...
function info(){
var ss = SpreadsheetApp.getActiveSheet();
var data = ss.getRange("N1:N").getValues();
for(var n=0;n<data.length;n++){
if(data[n-1] != 'done'){
var email = ss.getRange("F"+n).getValue(); // Range not found error
var fname = ss.getRange("D"+n).getValue();
var lname = ss.getRange("E"+n).getValue();
var city = ss.getRange("I"+n).getValue();
var street = ss.getRange("H"+n).getValue();
var phone = ss.getRange("G"+n).getValue();
var date = ss.getRange("A"+n).getValue();
var work = ss.getRange("B"+n).getValue();
var photo = ss.getRange("C"+n).getValue();
var site = ss.getRange("L"+n).getValue();
var find = ss.getRange("J"+n).getValue();
var referrer = ss.getRange("K"+n).getValue();
var contact = ContactsApp.createContact(fname, lname, email);
var group = ContactsApp.getContactGroup('emf');
group.addContact(contact);
var contacts = ContactsApp.getContactsByName(fname + ' ' + lname);
var setaddress = contacts[0].addAddress(ContactsApp.Field.HOME_ADDRESS,street + " " + city);
var setphone = contacts[0].addPhone(ContactsApp.Field.MAIN_PHONE,phone);
for (var i in contacts) {
contacts[i].setNotes(date + "\n\n" + work + "\n\n" + photo + "\n\n" + site + "\n\n" + find + " " + referrer + "\n\n-- eom --\n\n");}
}
}
}
1 is the first row using A1Notation with getRange(). The first iteration is trying to getValue() of F0. Changing the n to start at 1 and n <= data.length should get the ranges you are looking for.
...
for(var n=1;n<=data.length;n++){
if(data[n-1] == 'done'){
var email = ss.getRange("F"+n).getValue(); // Range not found error
...
edit: One thing to note the var data = ss.getRange("N1:N").getValues(); range is going to loop over all 1000 default rows. This may not be ideal if your data set is significantly smaller than 1000 rows.
I am trying to add an extra column to the HTML report. Like duration of each "it" block. I tried this inside jsonparser.js file.
phssr.makeHTMLPage = function(tableHtml, reporterOptions){
var styleTag = phssr.makeHardCodedStyleTag(reporterOptions);
var scrpTag = phssr.makeScriptTag();
var staticHTMLContentprefix = "<html><head><meta charset='utf-8'/>";
//Add title if it was in config setup
if (typeof (reporterOptions.docTitle) !== 'undefined' && _.isString(reporterOptions.docTitle) ){
staticHTMLContentprefix += "<title>" + reporterOptions.docTitle + "</title>";
} else {
staticHTMLContentprefix += "<title></title>";
}
staticHTMLContentprefix += styleTag + scrpTag + " </head><body>";
staticHTMLContentprefix += "<h1>" + reporterOptions.docHeader + "</h1><table class='header'>";
staticHTMLContentprefix += "<tr><th class='desc-col'>Description</th><th class='status-col'>Passed</th>";
staticHTMLContentprefix += "<th class='browser-col'>Browser</th>";
staticHTMLContentprefix += "<th class='os-col'>OS</th><th class='msg-col'>Message</th>";
staticHTMLContentprefix += "<th class='msg-col'>Duration</th>";
staticHTMLContentprefix += "<th class='img-col'>Screenshot</th></tr></table>";
var staticHTMLContentpostfix = "</body></html>";
var htmlComplete = staticHTMLContentprefix + tableHtml + staticHTMLContentpostfix;
return htmlComplete;
}
phssr.getTimestamp = function (date) {
function pad(n) { return n < 10 ? '0' + n : n; }
var currentDate = date !== undefined ? date : new Date(),
month = currentDate.getMonth() + 1,
day = currentDate.getDate();
return (currentDate.getFullYear() + "-" + pad(month) + "-" + pad(day) + " " + pad(currentDate.getHours()) + ":" + pad(currentDate.getMinutes()) + ":" + pad(currentDate.getSeconds()));
}
var sTime = new Date();
var startTime = phssr.getTimestamp(sTime);
console.log("sTime***********************",startTime);
var passCount=0, failCount=0, loopCount=0;
function generateHTML(data){
var eTime = new Date();
var endTime = phssr.getTimestamp(eTime);
console.log("eTime***********************",endTime);
var diffTime = (eTime-sTime)/1000;
console.log("dTime***********************",diffTime);
data.passed? passCount++: failCount++;
var str = '<table><tr>';
str += '<td class="desc-col">' + data.desc + '</td>';
var bgColor = data.passed? 'green': 'red';
str += '<td class="status-col" style="color:#fff;background-color: '+ bgColor+'">' + data.passed + '</td>';
str += '<td class="browser-col">' + data.browser.name+ ':' +data.browser.version + '</td>';
str += '<td class="os-col">' + data.os + '</td>';
var stackTraceInfo = data.passed? '': '<br/><a onclick="showTrace(event)" href="#trace-modal'+loopCount+'">View Stack Trace Info</a><br/> <div id="#trace-modal'+loopCount+'" class="traceinfo"><div>X' + data.trace + '</div></div>';
str += '<td class="msg-col">' + data.message+ stackTraceInfo+ '</td>';
str += '<td class="msg-col">' + diffTime + '</td>';
if(!(reporterOptions.takeScreenShotsOnlyForFailedSpecs && data.passed)) {
str += '<td class="img-col">View </td>';
}
else{
str += '<td class="img-col"></td>';
}
str += '</tr></table>';
loopCount++;
return str;
}
I can see the extra column in the report. The problem was it is not showing the correct time. In the console it is printing like this
sTime*********************** 2015-08-28 13:26:44
Using the selenium server at http://localhost:4444/wd/hub
.eTime*********************** 2015-08-28 13:26:48
dTime*********************** 3.312
.eTime*********************** 2015-08-28 13:26:52
dTime*********************** 7.984
eTime*********************** 2015-08-28 13:26:52
dTime*********************** 7.984
.
Finished in 12.123 seconds
3 tests, 3 assertions, 0 failures
eTime*********************** 2015-08-28 13:26:57
dTime*********************** 12.325
eTime*********************** 2015-08-28 13:26:57
dTime*********************** 12.325
eTime*********************** 2015-08-28 13:26:57
dTime*********************** 12.325
here, I don't know why it is executing two times. In the report it is showing 12.325 for all blocks. I don't know where I am doing wrong. please help me.
Tests:
describe('Title', function() {
it('TESTCASE-1 : Should have a title', function() {
expect(browser.getTitle()).toContain('Test');
});
it('TESTCASE-2 : Should accept a valid email address and password', function() {
element(by.id('email')).sendKeys('*********');
element(by.id('password')).sendKeys('*********');
element(by.css('.btn')).click();
expect(browser.getCurrentUrl()).toEqual('*********/app/#/home');
});
it('TESTCASE-4: Dashboard Selection.....', function(){
var menubutton = element.all(by.css('.btn')).get(0);
menubutton.click();
expect(browser.getCurrentUrl()).toEqual('*************************/students/1');
});
});
I had a broken code which I have managed to get working (The original question is here https://stackoverflow.com/questions/29127005/multiple-spreadsheet-rows-from-multiple-forms), but the loop writes the last line twice and my coding skills are not good enough for me to work out why...yet!
Can anyone shed any light on what I have/haven't included?
function InsertDataInSheet(e) //Function to insert data into spreadsheet on clicking submit
{
var app = UiApp.getActiveApplication();
//get number of rows to input
var num = parseInt(e.parameter.table_tag);
var num = num+1;
//set increment step through
for (var i = 1; i < num ; i++ ) {
//Declare varialbe fields to collect data from
var user = Session.getActiveUser().getEmail();
var date = e.parameter['DateBox'+i];
var location = e.parameter['LocationListBox'+i];
var source = e.parameter['SourceListBox'+i];
var reporter = e.parameter['ReporterTextBox'+i];
var priority = e.parameter['PriorityListBox'+i];
var hazard = e.parameter['HazardListBox'+i];
var details = e.parameter['DetailsTextBox'+i];
var description = e.parameter['DescriptionTextBox'+i];
var timeStamp = new Date();
//Decide date that this needs to be closed by
if (priority === '02 - WITHIN 24-48 HOURS') {
var dateTemp = new Date(date);
dateTemp.setDate(dateTemp.getDate()+2);
var actiondate = dateTemp;
}
if (priority === '03 - WITHIN 1 WEEK') {
var dateTemp = new Date(date);
dateTemp.setDate(dateTemp.getDate()+7);
var actiondate = dateTemp;
}
//establish email addresses
//Declare correct range to obtain values
var LocationSheet = SpreadsheetApp.openById(itemSpreadsheetKey).getSheetByName("LocationCodes")
//Start with central maintenance department
var email00 = LocationSheet.getRange(33,5).getValue()
//followed by other emails as they appear
var email01 = LocationSheet.getRange(3,5).getValue();
var email02 = LocationSheet.getRange(4,5).getValue();
//declare the correct Depots to check
var LocationSheet = SpreadsheetApp.openById(itemSpreadsheetKey).getSheetByName("LocationCodes");
var depot01 = LocationSheet.getRange(3,4).getValue();
var depot02 = LocationSheet.getRange(4,4).getValue();
//if source is recorded as '08 - Maitenance Request System', the recipient is maintenance deparment
if (source === "08 - Maintenance Request System"){
var recipient = email00;
//or depots as listed
} else if(location === depot01){
var recipient = email01;
} else if(location === depot02){
var recipient = email02; }
else {
//and send an email to the error catch all if no code supplied
var recipient = email00; //change as necessary
}
var sheet = SpreadsheetApp.openById(itemSpreadsheetKey).getSheetByName('LOG');
var lastRow = sheet.getLastRow();
var lrp1 = lastRow+1
var targetRange = sheet.getRange(lastRow+1, 1, 1, 12).setValues([[timeStamp,date,source,location,reporter,user,hazard,details,description,priority,recipient,actiondate]]);
//Notification Page
app = UiApp.getActiveApplication().remove(0);
app.createVerticalPanel()
.setId('info')
.setVisible(true)
.setStyleAttribute('left', 10)
.setStyleAttribute('top', 10)
.setStyleAttribute('zIndex', '1')
.setStyleAttribute('position', 'fixed')
.setStyleAttribute('background', 'white')
.setHeight('400px')
.setStyleAttribute('text-align', 'center')
.setBorderWidth(1)
.setWidth('500px');
app.add(app.createLabel('Your submission has been added to the database & the Site Coordinator will be emailed with notification.'));
// app.add(app.createLabel('The details you entered were recorded as:'));
// app.add(app.createLabel('Username: [' +user+ '] Timestamp: [' +timeStamp+ '] Reporter: [' +reporter+ ']'));
// app.add(app.createLabel('Location: [' +location+ '] Hazard: [' +hazard+ '] Source: [' +source+ ']'));
// app.add(app.createLabel('You listed the priority as: [' +priority+ '], please be aware this may not be the same priority given by the Site Coordinator responsible.'));
app.add(app.createLabel('Please refresh this page to submit more entries'));
return app.close();
}
var sheet = SpreadsheetApp.openById(itemSpreadsheetKey).getSheetByName("LOG");
var lastRow = sheet.getLastRow();
var lrp1 = lastRow+1
//Amend [getRange(lastRow+1, 1, 1, **)] integer to reflet number of headers being written if more added
var targetRange = sheet.getRange(lastRow+1, 1, 1, 12).setValues([[timeStamp,date,source,location,reporter,user,hazard,details,description,priority,recipient,actiondate]]);
var Body = 'A new [' +source+ '] log entry has been recorded at [' +location+ '], listed as [' + hazard+ ']. This form was submitted by [' +user+ '] with the timestamp [' +timeStamp+ '].'
}
The reason why it is adding last row twice is that because the following code is repeated after the loop:
var sheet = SpreadsheetApp.openById(itemSpreadsheetKey).getSheetByName("LOG");
var lastRow = sheet.getLastRow();
var lrp1 = lastRow+1
//Amend [getRange(lastRow+1, 1, 1, **)] integer to reflet number of headers being written if more added
var targetRange = sheet.getRange(lastRow+1, 1, 1, 12).setValues([[timeStamp,date,source,location,reporter,user,hazard,details,description,priority,recipient,actiondate]]);
var Body = 'A new [' +source+ '] log entry has been recorded at [' +location+ '], listed as [' + hazard+ ']. This form was submitted by [' +user+ '] with the timestamp [' +timeStamp+ '].'
Hope that helps!
Thanks KRR, I sorted it with that and the moving of one of the "}" from after the notification page to just before it. The corrected code is:
var sheet = SpreadsheetApp.openById(itemSpreadsheetKey).getSheetByName('LOG');
var lastRow = sheet.getLastRow();
var lrp1 = lastRow+1
var targetRange = sheet.getRange(lastRow+1, 1, 1, 12).setValues([[timeStamp,date,source,location,reporter,user,hazard,details,description,priority,recipient,actiondate]]);
}
///// TRAIL NOTIFICATION PAGE FROM WITHIN SYSTEM FROM HERE /////
app = UiApp.getActiveApplication().remove(0);
app.createVerticalPanel()
.setId('info')
.setVisible(true)
.setStyleAttribute('left', 10)
.setStyleAttribute('top', 10)
.setStyleAttribute('zIndex', '1')
.setStyleAttribute('position', 'fixed')
.setStyleAttribute('background', 'white')
.setHeight('400px')
.setStyleAttribute('text-align', 'center')
.setBorderWidth(1)
.setWidth('500px');
app.add(app.createLabel('Your submission has been added to the database & the Site Coordinator will be emailed with notification.'));
// app.add(app.createLabel('The details you entered were recorded as:'));
// app.add(app.createLabel('Username: [' +user+ '] Timestamp: [' +timeStamp+ '] Reporter: [' +reporter+ ']'));
// app.add(app.createLabel('Location: [' +location+ '] Hazard: [' +hazard+ '] Source: [' +source+ ']'));
// app.add(app.createLabel('You listed the priority as: [' +priority+ '], please be aware this may not be the same priority given by the Site Coordinator responsible.'));
app.add(app.createLabel('Please refresh this page to submit more entries'));
return app.close();
}
I have a social app for which I am trying to create a friend activities feed using Azure Sql Server.
I have 3 tables I want to select from:
Songs
-createdAt
-id
-userId
-trackName
-etc
Comments
-createdAt
-id
-userId
-songId
-text
Likes
-createdAt
-id
-userId
-songId
I have the users that the current user is following stored in an array named 'follows'.
How do I go about selecting the 40 most recent items from those 3 tables where userId in each table is in the follows array?
Edit:
function getActivities(userId) {
var deferred = Q.defer();
var follows = [];
getFollowing(userId).then(function (results) {
follows.push(userId);
_.each(results, function (user) {
follows.push(user.toUserId);
});
return;
}).then(function () {
var stringified = "'" + follows.join("','") + "'";
var queryString = "SELECT * FROM comments, songs, likes WHERE comments.userId IN (" + stringified + ") OR songs.userId IN (" + stringified +") OR likes.userId IN (" + stringified + ")";
var params = [];
return sqlQuery(queryString, params);
}).then(function (results) {
console.log('Activities: ', results);
deferred.resolve(results);
}, function (error) {
console.log('Error: ', error.message);
deferred.reject(error.message);
});
return deferred.promise;
}
Alright, so I dug into JOINS a little more and realized how easy it actually is once you wrap your head around it. Here is what I did to complete this:
var queryString = "SELECT TOP 50 follows.id AS followId, follows.toUserId AS followToUserId, follows.fromUserId AS followFromUserId, comments.text AS commentText, profiles.userId, profiles.username, profiles.name, profiles.profileImage, songs.trackId, songs.trackName, songs.artistName, songs.collectionName, songs.artworkUrl100, songs.caption, songs.id AS songId, activities.id AS activityId, activities.type AS activityType, activities.objectId AS activityObjectId, activities.parentType AS activityParentType, activities.parentId AS activityParentId, activities.__createdAt AS activityCreatedAt FROM activities ";
queryString += "INNER JOIN profiles ON (profiles.userId = activities.userId) ";
queryString += "LEFT JOIN songs ON (songs.id = activities.objectId AND activities.type = 'songs') OR (songs.id = activities.parentId AND activities.parentType = 'songs') ";
queryString += "LEFT JOIN comments ON (activities.type = 'comments' AND comments.id = activities.objectId) ";
queryString += "LEFT JOIN follows ON (activities.type = 'followed' AND activities.userid = follows.fromUserId) ";
queryString += "WHERE activities.userId IN (SELECT follows.toUserId AS userId FROM follows WHERE follows.fromUserId = ? AND follows.isFollowed = 'true') ";
queryString += "ORDER BY activities.__createdAt DESC";
var params = [userId];
mssql.query(queryString, params, {
success: function (results) {
_.each(results, function (result) {
//Remove columns with null or undefined values
for (var i in result) {
if (result[i] === null || result[i] === undefined) {
delete result[i];
}
}
});
response.send(200, results);
},
error: function (error) {
response.send(400, error.message);
}
});
I've been trying to send data to a web API VIA post. But it doesn't seem to be sending it.
Here's how I do it.
var baseAddress = "http://192.168.0.103/vchatapi/api/Images?gsmNumber=" + profileNumberLbl.Content + "&content=" + base64 + "&contentType=image/" + contentType;
var http = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new System.Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";
This code works with get:
var baseAddress = "http://192.168.0.103/vchatapi/api/SendSMSVerificationCode?gsmNumber=" + areCode + mobile + "&udid=123456";
var http = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new System.Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "GET";
try
{
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
verificationCode = verificationCode.FromJson(content);
if (!verificationCode.Equals(""))
{
MessageBox.Show(this, "Verification Code: " + verificationCode);
verificationTextBox.IsEnabled = true;
areaCodeCB.IsEnabled = false;
mobileNumberTB.IsEnabled = false;
}
else
{
MessageBox.Show(this, "Invalid Number");
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message);
}
Any ideas? Thanks!
Since you are doing a POST, you would be sending the content in the body of the request. You would need to get hold of the request's stream and write data to it. The following answer post has a very concise example:
https://stackoverflow.com/a/2551006/1184056