How to send data with XMLHttpRequest without passing data as parameter - javascript

Currently I am sending the data as parameter in URL.
Ex
var url = "http://localhost:8080/test?param1=" + param1Value+ "&param2="+ param2Value;
I am using XMLHttpRequest to communicated.
But by doing this I can see the params in requested URL.
How can I send the data without passing as parameter? (Basically how do I hide those data).
And on server how do I retrieve that?

You could simply use jquery to create a POST form, fill it up, and submit it on the fly.
$("body").append("<form id='form1' action='http://localhost:8080/test' method='POST'></form>");
$("<input></input>", {
"type": "text",
"name": "param1",
"value": param1Value
}).appendTo("#form1");
$("<input></input>", {
"type": "text",
"name": "param2",
"value": param2Value
}).appendTo("#form1");
var theForm = $("#form1");
theForm.hide();
theForm.submit();

Related

How to collect data from form entries when editing a previously submitted form using Google Apps Script?

I have a Google form that allows users to edit a previously submitted response. When a form is submitted the first time, I capture the timestamp, serial # and tech as variables and push them to a slack channel as a chat notification along with writing all of the responses to a spreadsheet. I am using an onFormSubmit trigger for the function. This part works great.
There are fields that are not required, but are filled out later by editing the form responses. When the form is edited and submitted, the serial # and tech fields are not changed. The spreadsheet is updated accordingly, but for the slack channel notification, the only variable that has data is the timestamp. The serial and tech are blank due to those fields not changing on the form. How do I create a variable for serial and tech using the pre-existing form response for my slack notification?
My current code checks if the tech value is blank or not and if not blank it sends a slack notification. If it is blank, it does nothing. If it is blank, I want it to capture the existing form responses as an array that I can use the values to create a slack notification showing the same data, but include that the original form has been re-submitted with the pre-existing values.
I am new to coding and have been researching and testing for over a week with no results.
var timestamp = 'Timestamp' //type exact column header as shown in workbook
var tech = 'Troubleshooting Tech' //type exact column header as shown in workbook
var parts = 'Part(s)# Ordered' //type exact column header as shown in workbook
var serial = 'Serial #' //type exact column header as shown in workbook
var slackWebHook = '' //Paste Slack webhook here
function SendSlackMessageEvent(e) {
const ss = SpreadsheetApp.getActive();
let data = e.namedValues
let payload = buildAlert(data);
if (data[tech] == '') {
}
if (data[tech] != '') {
sendAlert(payload);
}
}
function buildAlert(data) {
let timestampe = data[timestamp];
let teche = data[tech];
let seriale = data[serial];
let partse = data[parts];
let payload = {
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": ":bell: *Breakfix Ticket Submitted* :bell:"
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": teche + " submitted a ticket on " + timestampe
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Serial #: " + seriale
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Parts Needed: " + partse
}
}
]
};
return payload;
}
function sendAlert(payload) {
// const webhook = ""; //Paste your webhook URL here
const webhook = slackWebHook; //slack webhook URL
var options = {
"method": "post",
"contentType": "application/json",
"muteHttpExceptions": true,
"payload": JSON.stringify(payload)
};
try {
UrlFetchApp.fetch(webhook, options);
} catch(e) {
Logger.log(e);
}
}
The problem in your code is that you are assuming that an unchanged response will be included in the namedValues properties as an empty string but it will not be included so:
data[tech] will return undefined
Instead of
if (data[tech] == '') {
}
if (data[tech] != '') {
sendAlert(payload);
}
you might use
if(data[tech]){
// add here what should be done when data[tech] has a value
} else {
// add here what should be done when data[tech] is undefined
}
By the other hand, since the form submit event object includes a range property having the response corresponding range you could use it instead of namedValues property:
e.range.getValues() return Array holding a Array with the values logged in the spreadsheet.
Related
e.values in google forms skips empty answers, is there a workaround?
Reference
https://developers.google.com/apps-script/guides/triggers/events#form-submit

Read PDF file in JavaScript and send the data through an API

I'm basically looking for functionality equivalent to this Python code in JS:
It read a pdf file and send the bytes through a Post request
from requests import get, post
source = "my_pdf.pdf"
with open(source, "rb") as f:
data_bytes = f.read()
post_url = "my_url"
resp = post(url = post_url, data = data_bytes)
At the moment I'm using the react-jsonschema-form library, which has and option to read/load files form the following code:
{
"title": "Files",
"type": "object",
"properties": {
"file": {
"type": "string",
"format": "data-url",
"title": "Single file"
}
}
}
The above json schema generates this form:
With that I can load a file form my computer:
But from here, I don't know how to send the data to an API

How to use API translate of SAP Leonardo?

I need help with API translation of SAP Leonardo. I building a translation app for studing, and following the documentation a create the method translate:
translate: function () {
//Create JSON Model with URL
var oModel = new sap.ui.model.json.JSONModel();
var langTo = this.getView().byId("idTo").getSelectedKey();
var langFrom = this.getView().byId("idFrom").getSelectedKey();
var textOld = this.getView().byId("idOldText").getValue();
//API Key for API Sandbox
var sHeaders = {
"Content-Type": "application/json",
"APIKey": "My api Key"
};
//Available Security Schemes for productive API Endpoints
//OAuth 2.0
//sending request
//API endpoint for API sandbox
var oData = {
"sourceLanguage": langTo,
"targetLanguages": [
langFrom
],
"units": [{
"value": textOld,
"key": "ANALYZE_SALES_DATA"
}]
};
oModel.loadData("https://sandbox.api.sap.com/ml/translation/translation", oData, true, "POST", null, false, sHeaders);
//Available API Endpoints
//https://mlfproduction-machine-translation.cfapps.eu10.hana.ondemand.com
//https://mlfproduction-machine-translation.cfapps.us10.hana.ondemand.com
//You can assign the created data model to a View and UI5 controls can be bound to it. Please refer documentation available at the below link for more information.
//https://sapui5.hana.ondemand.com/#docs/guide/96804e3315ff440aa0a50fd290805116.html#loio96804e3315ff440aa0a50fd290805116
//The below code snippet for printing on the console is for testing/demonstration purpose only. This must not be done in real UI5 applications.
oModel.attachRequestCompleted(function (oEvent) {
var oData = oEvent.getSource().oData;
// console.log(oData);
});
}
I used two selectBox for to get language keys both calls "idTo" and "idFrom". And I used too a input for get a text will be translate with id "idOldText". But nothing happen. the oData value always empty in the last instruction. I'm used SAP WEBIDE and I guess that it is not need configure IDE for to use the API.
Someone can help me?
it would be helpful if you provide the error from your console.
But I already have a feeling that this ends up in a cross site request, and thus will be blocked because of using a full qualified URL. Also your header whitelist is maybe missing.
Do it like this and it should work:
1) create a destination in SAP CP
2) create a new sapui5 project in SAP WebIDE and adapt neo-app.json by addin a new destination path and header whitelist your request headers
{
"welcomeFile": "/webapp/index.html",
"routes": [{
"path": "/resources",
"target": {
"type": "service",
"name": "sapui5",
"entryPath": "/resources"
},
"description": "SAPUI5 Resources"
}, {
"path": "/test-resources",
"target": {
"type": "service",
"name": "sapui5",
"entryPath": "/test-resources"
},
"description": "SAPUI5 Test Resources"
}, {
"path": "/ml-dest",
"target": {
"type": "destination",
"name": "sapui5ml-api"
},
"description": "ML API destination"
}],
"sendWelcomeFileRedirect": true,
"headerWhiteList": [
"APIKey", "Accept", "Content-Type"
]
}
3) add your method and post the request || possible issues in your version: JSON object and request headers
onInit: function () {
var oModel = new sap.ui.model.json.JSONModel();
var sHeaders = {
"Content-Type": "application/json",
"Accept": "application/json",
"APIKey": "<<yourAPIKey>>"
};
var oData = {
"sourceLanguage": "en",
"targetLanguages": [
"de"
],
"units": [{
"value": "I would like to analyze my sales data.",
"key": "ANALYZE_SALES_DATA"
}]
};
var ODataJSON = JSON.stringify(oData);
oModel.loadData("/ml-dest/translation/translation", ODataJSON, true, "POST", null, false, sHeaders);
oModel.attachRequestCompleted(function (oEvent) {
var oData = oEvent.getSource().oData;
console.log(oData.units[0].translations[0]);
});
}
4) get a successful response object when loading your app :-)
References used:
Destination creation (my own blog entry btw.) https://blogs.sap.com/2018/09/05/successfactors-extensions-with-sapui5-and-the-correct-usage-of-sap-cp-destination-services/
SAPUI5 examples for SAP ML Inference Services (see multiple examples) https://developers.sap.com/tutorials/ml-fs-sapui5-img-classification.html

JAVASCRIPT editing headers to call api that returns json

I am trying to use an API that is hosted externally and also returns JSON data. I have tried editing the headers but I'm not entirely sure it is working because I am still getting a warning about not having the CORS header
Source
var url = "http://hkconsult.in/social_search/keyword_services.php?keyword=throat&callback=test";
$.ajax({
type: 'get',
url: url,
headers: {
"Origin":"http://hkconsult.in/social_search/keyword_services.php?keyword=throat&callback=test",
"Access-Control-Allow-Origin":"http://hkconsult.in/social_search/keyword_services.php?keyword=throat&callback=test"
}
}).done(function(data) {
document.getElementById('cool').innerHTML = data;
});
Firebug Headers
When opening the response for the "OPTIONS" url in firebug, it returns the data that I want. How do I use that data in javascript?
The CORS are headers that the server should send you as a response to your request.
The OPTIONS request is performed by the browser to check those headers prior to performing your actual request.
You cannot get the result of that OPTIONS request because it happens outside the scope of your code.
If the server is not setup to send those headers, then your only option is to use a proxy page that will use a server-side script to perform the call on your behalf.
As per my understanding you are asking about how to parse the response JSON instead of CORS Issue.
var data = {
"0": {
"keyword_name": "Sore throat",
"id": "1787",
"user_id": "3350988339",
"user_name": "Nic",
"user_screen_name": "Goldendevi",
"user_profile_pic": "http://pbs.twimg.com/profile_images/840766770633945088/eRRoRZHv_normal.jpg",
"user_location": "",
"post_id": "864553159896838145",
"post_text": "I'm so mad I have a fucking sore throat 🙄",
"post_geo_location": "0",
"post_image": "",
"post_date": "2017-05-16 20:48:30"
},
"1": {
"keyword_name": "Sore throat",
"id": "1788",
"user_id": "63496454",
"user_name": "mariana",
"user_screen_name": "yugyeumie",
"user_profile_pic": "http://pbs.twimg.com/profile_images/863802594132733952/ep0DtSoT_normal.jpg",
"user_location": "jjp; 맠슨",
"post_id": "864552988974747649",
"post_text": "is it possible to die of a sore throat",
"post_geo_location": "0",
"post_image": "",
"post_date": "2017-05-16 20:47:49"
}
};
var res = Object.keys(data).map(item => {return data[item].keyword_name });
console.log(res);

Jquery Autocomplete with json fails

I am using the auto complete plugin by Devbridge and I have it all installed here is my code:
$(document).ready(function(){
$('#request_task').autocomplete({
serviceUrl: '<%= ajax_path %>',
minChars:1,
width: 300,
delimiter: /(,|;)\s*/,
deferRequestBy: 0, //miliseconds
params: { artists: 'Yes' },
});
});
This request hits my rails action and returns this json. there is only one object returned but most of the time there will be more then 1...this was just a test case:
[
{
"user": {
"salt": "somthing",
"name": "john",
"encrypted_password": "92dadsfa6b001ffe71c3c1d8e9fb76c42d1c8afeffa739de9063d94206c",
"created_at": "2010-09-10T14:10:54Z",
"updated_at": "2010-09-10T14:10:54Z",
"admin": null,
"id": 1,
"remember_token": "c945522b3eb0a25e36bb39155fc05b3eec301ac5e2196956f2e6f86b4b22c987",
"email": "test#gmail.com"
}
}
]
I can clearly see the request in firebug but I am not getting anything for the autocomplete and it errors out...Am i missing anything...My error is
a.suggestions is undefined
I think you need to read a little further down the developers page as your response is in the wrong format:
Web page that provides data for Ajax
Autocomplete, in our case
autocomplete.ashx will receive GET
request with querystring ?query=Li,
and it must return JSON data in the
following format:
{
query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']
}
Notes:
query - original query value
suggestions - comma separated array of suggested values data
(optional) - data array, that contains values for callback function when data is selected.
Sincere advice , dont construct JSON Strings. Please go for an API.
If you are using java, check this out http://www.json.org/java/
and make sure to set content-type in response as application/json
YOUR JSON is in a wrong format
Check their correct format
{
query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']
}

Categories

Resources