Better way to pass data to server? - javascript

So I am using query strings to pass data from a form to my server. The query strings look like this:
this.$http.post('http://localhost:3000/operation?Stime='+this.Stime+'&Etime='+this.Etime+'&eAMPM='+this.eAMPM+'&sAMPM='+this.sAMPM+'&id='+this.id+'&activity='+this.activity+'&auto_insert='+this.auto_insert+'&yearmonthday='+this.yearmonthday+'&color1='+this.c)
and In my server I have all these variables to store the query's variables:
var color = req.query.color1;
var Stime = req.query.Stime;
var Etime = req.query.Etime;
var sAMPM = req.query.sAMPM;
var eAMPM = req.query.eAMPM;
var id = req.query.id;
var activity = req.query.activity;
var requestAccepted = req.query.requestAccepted;
var yearmonthday = req.query.yearmonthday;
var auto_insert = req.query.auto_insert;
It just seems like a lot of code to just post my variables to the server (It works just fine) but I was wondering if there were some ways I could refactor it/ make it cleaner

Of course there is!
Consider doing some research into the HTTP message body:
A message body is the one which carries the actual HTTP request data (including form data and uploaded, etc.) and HTTP response data from the server ( including files, images, etc.).
In your case, you can change your Angular $http POST request to as follows -
var data = {
Stime: '+this.Stime+',
Etime: '+this.Etime+',
eAMPM: '+this.eAMPM+',
sAMPM: '+this.sAMPM+',
id: '+this.id+',
activity: '+this.activity+',
auto_insert: '+this.auto_insert+',
yearmonthday: '+this.yearmonthday+',
color1: '+this.c+'
}
$http({
method: 'POST',
url: 'http://localhost:3000/operation',
data: JSON.stringify(data)
})

Related

Nodejs not applying script id value passed to it

I am writing a program in nodejs using the request-promise-native module to create a startup script,receive the script ID then create a server and apply the script ID, however even after gathering the script ID and passing it to the request to create the server it does not get applied. I have made sure that the value of the variable I am passing for the scriptID is in the correct form of data type but it still seems not to work for some reason
var scriptRequest = require('request-promise-native');
var serverRequest = require('request-promise-native');
var headers = {
'API-Key': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
};
var scriptOptions = {
url: "https://api.vultr.com/v1/startupscript/create",
method: "POST",
headers: headers,
form: {
name: "test script",
script: "#!/bin/bash \napt-get update (not the actual script, just shortened it since the script itself is long and as of now the vultr server doesn't even make it this far)"}
};
var serverOptions = {
url: 'https://api.vultr.com/v1/server/create',
method: 'POST',
headers: headers,
form: {
DCID: '6',
VPSPLANID: '202',
OSID: '215',
SCRIPTID: scriptResponse
}
};
var scriptResponse;
async function main(){
const response = await scriptRequest({...scriptOptions, json:true})
const json = response.SCRIPTID
scriptResponse = json
await serverRequest(serverOptions)
}
main()
as you can see I have had to make the scriptRequest variable global, if I try to set it in the main function it gives me an undefined error in the serverOptions block
EDIT: just to clarify, the script ID I want to apply to the scriptResponse variable is returned upon making the scriptRequest post request

Ho do I Parse XML using Google Apps Script and loop through all elements

This is my first time working with XML and I am not that techy but trying to get to understand programming to make my work easier. I am using Google App script and finding it a challenge in passing XML data that I get via API.
I need to get this data so that I can set the specific values to Google sheets using google app script.
I am not sure how to iterate/loop through elements to get everyone's data and then set it to google sheet.
And here is the code I have worked on so far. When I log to say the first name, I only get one name instead of about 50 names in the system. Any help here will highly be appreciated.
ak ='key'
start = '2019-01-01'
end = '2019-12-31'
function getData() {
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + ak
}
};
var url = 'https://data.purelyhr.com/daily?ak='+ ak + '&sDate=' + start + '&eDate=' + end + '&TimeOffTypeName';
var response = UrlFetchApp.fetch(url).getContentText();
var document = XmlService.parse(response);
var root = document.getRootElement();
//set variables to data from PurelyHR
var TimeOffDate = root.getChild('Request').getChild('TimeOffDate').getText();
var TimeOffDayOfWeek = root.getChild('Request').getChild('TimeOffDayOfWeek').getText();
var TimeStart = root.getChild('Request').getChild('TimeStart').getText();
var TimeEnd = root.getChild('Request').getChild('TimeEnd').getText();
var TimeOffHours = root.getChild('Request').getChild('TimeOffHours').getText();
var TimeOffTypeName = root.getChild('Request').getChild('TimeOffTypeName').getText();
var LoginID= root.getChild('Request').getChild('LoginID').getText();
var Firstname = root.getChild('Request').getChild('Firstname').getText();
var Lastname = root.getChild('Request').getChild('Lastname').getText();
var UserCategory = root.getChild('Request').getChild('UserCategory').getText();
var SubmittedDate = root.getChild('Request').getChild('SubmittedDate').getText();
var Deducted = root.getChild('Request').getChild('Deducted').getText();
var Comment = root.getChild('Request').getChild('Comment').getText();
//populate the sheet with variable data
Logger.log(response)
}
Sample response
<?xml version='1.0' encoding='ISO-8859-1'?>
<DataService>
<Request ID="1253" Status="Approved">
<TimeOffDate>2020-02-07</TimeOffDate>
<TimeOffDayOfWeek>Friday</TimeOffDayOfWeek>
<TimeStart></TimeStart>
<TimeEnd></TimeEnd>
<TimeOffHours>8.000</TimeOffHours>
<TimeOffTypeName>Annual Vacation</TimeOffTypeName>
<LoginID>testuser</LoginID>
<Firstname>test</Firstname>
<Lastname>user</Lastname>
<UserCategory></UserCategory>
<SubmittedDate>2019-10-03</SubmittedDate>
<Deducted>Yes</Deducted>
<Comment>
<![CDATA[* time-off request created by administrator]]>
</Comment>
</Request>
<Request ID="126292" Status="Approved">
<TimeOffDate>2020-02-07</TimeOffDate>
<TimeOffDayOfWeek>Friday</TimeOffDayOfWeek>
<TimeStart></TimeStart>
<TimeEnd></TimeEnd>
<TimeOffHours>8.000</TimeOffHours>
<TimeOffTypeName>Annual Vacation</TimeOffTypeName>
<LoginID>usertwo</LoginID>
<Firstname>user</Firstname>
<Lastname>two</Lastname>
<UserCategory></UserCategory>
<SubmittedDate>2019-10-15</SubmittedDate>
<Deducted>Yes</Deducted>
<Comment>
<![CDATA[Neil (as my mentor)]]>
</Comment>
</Request>
If I understand correctly, the problem is that you have multiple <Request> elements, but your code is only looking at one of them. This is because you're using getChild(), which will only provide the first element with the given name.
I can't fully test that this works because you haven't provided the XML text, but you should instead use the getChildren() method to get all of the Request elements. Then you can loop through that.
function getData() {
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + ak
}
};
var url = 'https://data.purelyhr.com/daily?ak=' + ak + '&sDate=' + start + '&eDate=' + end + '&TimeOffTypeName';
var response = UrlFetchApp.fetch(url).getContentText();
var document = XmlService.parse(response);
var root = document.getRootElement();
//set variables to data from PurelyHR
var requestElements = root.getChildren('Request'); // Get all <Request> elements
var requestObjects = []; // Request objects for logging / eventual printing
for (var i = 0; i < requestElements.length; i++) {
var request = requestElements[i]; // A single <Request> element
// Add to requestObjects array
requestObjects.push({
TimeOffDate: request.getChild('TimeOffDate').getText(),
TimeOffDayOfWeek: request.getChild('TimeOffDayOfWeek').getText(),
TimeStart: request.getChild('TimeStart').getText(),
TimeEnd: request.getChild('TimeEnd').getText(),
TimeOffHours: request.getChild('TimeOffHours').getText(),
TimeOffTypeName: request.getChild('TimeOffTypeName').getText(),
LoginID: request.getChild('LoginID').getText(),
Firstname: request.getChild('Firstname').getText(),
Lastname: request.getChild('Lastname').getText(),
UserCategory: request.getChild('UserCategory').getText(),
SubmittedDate: request.getChild('SubmittedDate').getText(),
Deducted: request.getChild('Deducted').getText(),
Comment: request.getChild('Comment').getText()
});
}
Logger.log(JSON.stringify(requestObjects));
}
Since I don't know how you're printing, I created an array of request objects and logged that in the sample above. I hope this made sense, but please let me know if you have any questions or if I'm completely off with my response.

Maintain Context

I'm trying to keep the context in Watson Conversation, but it isn't working.. I already tried this answer, but it didn't worked. I'm trying to integrate the bot to the html.
I tried this in the conversation configuration:
var payload = {
workspace_id: workspace,
context: {}};
if (req.body) {
if (req.body.input) {
payload.input = req.body.input;
}
if(req.body.context) {
payload.context = req.body.context;
}}
And this in the code to html/javascript:
var payload = {};
var context = {};
function callWatson(){
alert("watson");
$.ajax({
type: 'POST',
dataType: 'JSON',
contentType: "application/json",
url: '/api/message',
data: JSON.stringify(payload)
}).done(function (json) {
if (json.output.text[0]) {
context = payload.context;
$'<div class="message">+ json.output.text[0]+</div>').appendTo($('.container'));
function insertMessage() {
msg = $('.message-input').val();
$'<div class="message">+ msg+</div>').appendTo($('.container'));
I'm a beginner in coding and I tried coping the conversation-simple js, but I wanted something more simple and direct.. Thanks in advance!
For send message like Watson, with repository conversation-simple, you can simple add in your front-end:
var latestResponse = Api.getResponsePayload();
var context = latestResponse.context;
Api.setResponsePayload('{"output": {"text": ["Hi $name!"]},"context" : ' + JSON.stringify(context) +'}');
You can see the Javascript code use Api and getResponsePayload() and setResponsePayload function inside api.js (path public/js/api.js) to send a message like Watson. But, in your index you have to add the file for use like this line.
You can see inside my setResponsePayload I use the output and text to send the message, like payload show if Watson sends a message.
No need to waste time to maintain context just delete conversation_start dialog(first dialog node) in ibm watson conversation after that give input then you will get exact output
You could try using this as a starting point: https://github.com/snrubnomis/burgerbot
It's intended to be as simple as possible. The "sendMessage" function (in burgerbot.js) makes the call and then stores the returned context for use on subsequent calls.

Send HEAD request in Google App Script

I am developing a Google App Script to determine the size of a remote resource without downloading it. The code is as follows
function getRemoteFileSize()
{
var params = { "method" : "head" };
var resp = UrlFetchApp.fetch("https://www.google.com/images/srpr/logo11w.png", params);
Logger.log("Remote File Size: " + resp.getAllHeaders()["Content-Length"]);
}
However, Google App Script does not seem to support head requests and the code above cannot be executed.
What can be a viable alternative other than issuing a GET request ?
I am open to all suggestions including usage of a third-party service which has an API
You can try to override the method by setting the "headers" advanced parameter:
var params = {"method" : "GET", "headers": {"X-HTTP-Method-Override": "HEAD"}};
I've never used "HEAD", so I can't tell you for sure that this will work, but I have used the method override for "PATCH", and had that work.
I found that for my circumstance, I was able to use the Range header to request 0 bytes and then inspect the response headers which held the file size:
var params = {
method: "GET",
headers: {
Range: "bytes=0-0",
},
};
var response = UrlFetchApp.fetch(fileUrl,params);
var headers = response.getHeaders();
var fileSizeString = headers['Content-Range']
var fileSize = +headers['Content-Range'].split("/")[1];
The response headers had Content-Range=bytes 0-0/139046553 as a value that I could then use to convert to an integer (139046553) number of bytes.

Read XML from PHP - JQUERY AJAX POST - Not using XMLHTTP

I got some code off a tutorial a couple of months ago that I am now changing and using in my site. I have already coded alot so do not want to go another route.
Basically I need to retrieve all posts from a database and display on screen dynamically without refreshing the page. now I have the XML that is generated from the PHP file - all is good. Where I am stuck is reading that XML o the ajax side. here is what I have so far:
function getAllPosts() {
alert('hi');
var count = 0;
var tlu = getUrlVars()["user"]; // tlu stands for time line user
var data = 'user='+tlu;
$.ajax({
url: 'getAllPosts.php',
type: 'POST',
data: data,
success: function(response){
var xml = response.responseXML;
var posts = xml.documentElement.getElementsByTagName("post_item");
for (var i = 0; i < posts.length; i++) {
var id = posts[i].getAttribute("id");
var account_name = posts[i].getAttribute("account_name");
var author = posts[i].getAttribute("author");
var type = posts[i].getAttribute("type");
var data = posts[i].getAttribute("data");
var postdate = posts[i].getAttribute("post_date");
categoryPost(id, account_name, author, type, data, postdate);
}
}
});
}
function categoryPost(id, account_name, author, type, data, pastdate){
if(type === 'write'){
alert("hello");
}
}
It is running the alert("hi"); test but not the rest of the code.
My console gives me this: Uncaught TypeError: Cannot read property 'documentElement' of undefined
How can I read the elements from the xml? Everywhere I look has that XMLHTTP stuff and I don't, so I am pretty confused...
Thanks in Advance
If you are expecting an XML response, try setting data type: 'xml'. In your $.ajax parameters. If you're still having issues. Log the response object by using console.log(response) to examine what is actually being returned or you can use Chrome's postman extension. Comes in handy ;-).

Categories