I recently tested A LOT of different syntax for sending an ajax post request, and the only one which actually worked was the one I got from my Postman testing. The only problem I have now is the Postman code snippet is "hardcoded" and features a weird string syntax I have never seen before. I want to replace parts of that weird string with values from HTML inputs. Any ideas how I can achieve this?
I have two simple HTML inputs:
<input type="text" id="username" name="username" placeholder="Username" autofocus />
<input type="password" id="password" name="password" placeholder="Password" />
And here is the part I got from Postman (JavaScript):
var settings = {
"async": true,
"crossDomain": true,
"url": "...",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"cache-control": "no-cache"
},
"processData": false,
"data": "{ \r\n\"Username\":\"username123\",\r\n\"Password\":\"password123\"\r\n}"
}
$.ajax(settings).done(function(response) {
console.log(response);
});
Specifically, the part I'm asking about is the "data" line. I want to be able to take the values from the two HTML inputs, and replace "username123" and "password123" with them respectively. I have tried playing around with the data string, like removing \r\n and some " and \ , but then I get an error from the API I'm trying to call to. Do I really need all those? To be clear, I'm wondering how to put my variables into the string using valid syntax, not how to get the values like for example:
var usname = document.getElementById("username").val();
or
var usname = $('#username').val();
And these JSON syntax are tested and recieves an error:
"data": {"Username": "username123","Password": "password123"}
"data": "{"Username": "username123", "Password": "password123"}"
"data": {"Username": usname, "Password": pword}
"data": {"Username": $('username').val(), "Password": $('password').val()}
I feel like at least the first one should work, but it just comes back with error 500. For reference, here's what the body (data) looks like in Postman (working):
{
"Username":"username123",
"Password":"password123"
}
Could it be an issue with whitespace or something? I sadly don't have access to the source code of the API I'm calling.
I'm wondering how to put my variables into the string using valid
syntax
settings.data = settings.data.replace("username123", usname);
settings.data = settings.data.replace("password123", uspassword);
For formatting the data as JSON and the be able to use its properties for different purposes:
var settings = {
"async": true,
"crossDomain": true,
"url": "...",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"cache-control": "no-cache"
},
"processData": false,
"data": "{ \r\n\"Username\":\"username123\",\r\n\"Password\":\"password123\"\r\n}"
};
//remove line breaks
settings.data = settings.data.replace('/\r?\n|\r/', '');
//convert to properties
settings.data = JSON.parse(settings.data);
//re-assign properties as needed
settings.data.Username = 'newUsername';
settings.data.Password = document.getElementById('password').value;
console.log(settings.data);
<input type="password" id="password" name="password" placeholder="Password" value="newPassword"/>
I suggest to use a FormData to wrap the data you are going to send:
var formData = new FormData();
formData.append('Username', $("#username").val());
formData.append('Password', $("#password").val());
And later, you call the ajax post like this:
var settings = {
"async": true,
"crossDomain": true,
"url": "...",
"method": "POST",
"contentType": 'application/x-www-form-urlencoded',
"processData": false,
"data": formData
};
$.ajax(settings).done(function(response)
{
console.log(response);
});
If you need to send data as JSON then you can give a try to next code:
var data = {};
data.Username = $("#username").val();
data.Password = $("#password").val();
var settings = {
"async": true,
"crossDomain": true,
"url": "...",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"cache-control": "no-cache"
},
"processData": false,
"data": JSON.stringify(data)
};
$.ajax(settings).done(function(response)
{
console.log(response);
});
Related
I'm fairly new to APIs in general, I managed to post data into restdb but how can i go about creating a system to log in based on the user/account data that i posted previously? what i'm thinking is using get and checking if any email and password matches but that does not sound efficient to code or im not sure if its possible to. could someone point me in the right direction
This is how my post function looks
$(document).ready(function () {
const APIKEY = ".";
$("#account-submit").on("click", function (e) {
//prevent default action of the button
e.preventDefault();
let name = $("#name").val();
let contactEmail = $("#contact-email").val();
let studentID = $("#student-id").val();
let password = $("#password").val();
var jsondata = {
"name": name,
"email": contactEmail,
"studentid": studentID,
"password": password,
};
var settings = {
"async": true,
"crossDomain": true,
"url": "https://nerdge-d48f.restdb.io/rest/account",
"method": "POST",
"headers": {
"content-type": "application/json",
"x-apikey": ".",
"cache-control": "no-cache"
},
"processData": false,
"data": JSON.stringify(jsondata)
}
$.ajax(settings).done(function(response) {
console.log(response);
$("#account-submit").prop("disabled", false);
});
})
}
)
First of all what I am trying to do is accomplish the following.
Note: this is not my add-on.
How is this script generated? I cannot find any information about script.google.com/macros.
After this tab is closed, the add-on gets a callback that looks like this:
As I don't understand the flow my questions are:
How does the add-on script know that the tab is being closed?
How is the script created?
At which endpoint does the script call the google add-on?
The following is my add-on script:
function insertDocumentToRMS(e){
var url = "https://test.signumid.hr/v/1/rms";
var object = {
"data" : e.parameters.file.toString()
}
var payload = JSON.stringify(object);
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
};
var options = {
"method": "POST",
"contentType": "application/json",
"headers": headers,
"payload": payload,
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response.getContentText());
Logger.log(data);
var url2 = "https://test.signumid.hr/v/1/signer/document/storage/"+ data.recordNumber;
Logger.log(url2);
var object2 = {
"SignatureProvider": "SwisscomAis",
"SignatureProviderData": {
"SwisscomRequestData": {
"mobileNumber": "+41796063855",
"language": "en",
"message": "Matej PotpiĆĄiii!",
"jurisdiction": "ZERTES",
"signatureLevel": "AES"
}
},
"Documents": [
{
"SignatureOptions": {
"Reason": "Reason",
"Location": "Location",
"SignerContactInfo": "SignerContactInfo",
"SignerName": "SignerName"
},
"Document": e.parameters.file.toString()
}
]
}
var payload2 = JSON.stringify(object2);
var headers2 = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
};
var options2 = {
"method": "GET",
"contentType": "application/json",
"headers": headers2,
"payload": payload2,
"muteHttpExceptions": true
};
var response2 = UrlFetchApp.fetch(url2, options2);
Logger.log(response2);
let actionSign = CardService.newAction().setFunctionName('test');
var actionResponse = CardService.newActionResponseBuilder()
.setOpenLink(CardService.newOpenLink()
.setUrl("https://test.signumid.hr/v/1/signer/document/storage/"+ data.recordNumber)
.setOpenAs(CardService.OpenAs.OVERLAY)
.setOnClose(CardService.OnClose.RELOAD))
.build();
return actionResponse;
}
As you can see at the end (here), I am trying to use an actionBuilder with an actionResponse that has the property OnClose, but the only parameters on OnClose are: NOTHING and RELOAD. Can I pass an action somehow or what am I supposed to do to replicate the scenario that I mentioned above?
var actionResponse = CardService.newActionResponseBuilder()
.setOpenLink(CardService.newOpenLink()
.setUrl("https://test.signumid.hr/v/1/signer/document/storage/"+ data.recordNumber)
.setOpenAs(CardService.OpenAs.OVERLAY)
.setOnClose(CardService.OnClose.RELOAD))
.build();
Basically what the add-on is doing is a 'sign in workflow' to authorize scopes. If you want to replicate that workflow you can take a look at this sample provided by Google.
Aside from that you can submit a feature request to control browser events.
Looking for any alternative options I found this and this.
As for macros using Google Apps Script, you can look here.
I want to parse multiple files in one key in the Rails API.
and this is rails controller code.
def fun
render json: params[:file]
end
and this is javascript-jQuery code.
var form = new FormData();
form.append("file", fileInput.files[0], "75341083_406717103617108_7315677611286331392_n.jpg");
form.append("file", fileInput.files[0], "75380217_961903127500586_7366878762530504704_n.jpg");
var settings = {
"url": "http://127.0.0.1:3000",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/x-www-form-urlencoded"
},
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": form
};
$.ajax(settings).done(function (response) {
console.log(response);
});
and this is response
{
"tempfile": "#<File:0x00007fe4c4a289f0>",
"original_filename": "75380217_961903127500586_7366878762530504704_n.jpg",
"content_type": "image/jpeg",
"headers": "Content-Disposition: form-data; name=\"file\"; filename=\"75380217_961903127500586_7366878762530504704_n.jpg\"\r\nContent-Type: image/jpeg\r\n"
}
what can I do?
Give the params unique names so that they don't just overwrite each other in the params hash:
form.append("file", fileInput.files[0], "75341083_406717103617108_7315677611286331392_n.jpg");
form.append("other_file", fileInput.files[1], "75380217_961903127500586_7366878762530504704_n.jpg");
Or create an array in the params:
form.append("files[]", fileInput.files[0], "75341083_406717103617108_7315677611286331392_n.jpg");
form.append("files[]", fileInput.files[1], "75380217_961903127500586_7366878762530504704_n.jpg");
Or a hash:
form.append("files[first]", fileInput.files[0], "75341083_406717103617108_7315677611286331392_n.jpg");
form.append("files[second]", fileInput.files[1], "75380217_961903127500586_7366878762530504704_n.jpg");
A client wants to be able to make xmlhttp ajax requests with the default content type of content-type:"application/x-www-form-urlencoded; charset=UTF-8" but sending the data in the form the API expects application/json. So the request comes across as this:
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:80/api/metadata/taxonomy",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "62a245ad-a0a2-4dd3-bf84-37f622f00b7d"
},
"processData": false,
"data": "{\n\t\"practice\": [\"Learning\"]\n}"
}
$.ajax(settings).done(function (response) {
console.log(response);
});
But the API expects to be able to get req.body as a JSON object it can immediately use:
"{"practice":["Learning"]}"
Can I transform this "{\n\t\"practice\": [\"Learning\"]\n}" to this "{"practice":["Learning"]}" in some safe/suggested manner? (without some home grown parsing function or regex)
Yes, the JSON.parse function can be used for this:
try{JSON.stringify(JSON.parse(data))}
will convert strange json with newlines to standard one line string json.
JSON.parse
Parses the json into an object
JSON.stringify
Turns an object into a one line formatted JSON object
try
JSON.parse will fail if an invalid json string is passed. (\ns are valid in json.parse)
If this you meant converting "{\n\"your\":\n \"object\"}" to a javascript object like {"your": "object"}, you can just use try{JSON.parse(variablename)}
According to these answers, for older browsers you may need JSON-js
You can actually post JSON as body.
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:80/api/metadata/taxonomy",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "62a245ad-a0a2-4dd3-bf84-37f622f00b7d"
},
"dataType" : "json"
"processData": false,
"data": { "practice": ["Learning"] }
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Notice that theirs a new property which tells that data type to be posted is JSON and and now in data property the value is in JSON format instead of string.
Hope this solves your problem.
I have to hit a URL and get its encrypted data response back and use that encrypted data to decrypt data bu using a key.
I used POSTMAN to get the data response back but when I looked into it was just some symbols and not anything like a data response. So, it is encrypted.
I already have a function that convert the encrypted response back to plain text but now, I am not understanding how will I convert that data response to plain text as I have to first get that data response and then only use that data response in a parameter of a decrypto function and with the help of key I can change the back it to plain text.
I know how to change a cipher text to pln text but here things are little bit different.
But as I have to get the data response back shouldn't I have to make a POST request to get it or maybe I am understanding it wrong.
This is my decrypto function-
function decryptByDES(cipherTextString, keyString) {
var keyHex = CryptoJS.enc.Utf8.parse(keyString);
var decrypted = CryptoJS.DES.decrypt({
ciphertext: CryptoJS.enc.Base64.parse(cipherTextString)
}, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
alert(decrypted);
return decrypted.toString(CryptoJS.enc.Utf8);
}
Here when I calling it
<button onclick="decryptByDES('aHJHDJSHJhjsak=', 'ALSOWURNsa');">View</button>
I am giving or specifying the ciphertext string and key string as I using it only for testing there is no security issue. It is giving the decrypted value in alert-box.
So, in all I want to know how to get an encrypted data response and used that in the function so read it like a plain text.
EDIT:
With the help of POSTMAN I generated code for Javascript Ajax call
var settings = {
"async": true,
"crossDomain": true,
"url": "http://192.168.168.76:8080/HTMLPortingNewService/GetData?ChartName=widget3LineChart&lob=M&carrier=0&enrollmenttype=0&state=0&agent=0&fromdate=04%2F03%2F2015&todate=05%2F03%2F2015&requestID=499F6BF5E4610454A887AB37AF0814E8",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "ac20a050-a8c8-6d58-4350-66141d519394",
"content-type": "application/x-www-form-urlencoded"
},
"data": {
"username": "aHRtbHVzZXIx",
"password": "SHRtbDIwMTY="
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
So, now how I can call this response in my function??
You have to call decryptByDES after ajax complete.
function callServer(){
var settings = {
"async": true,
"crossDomain": true,
"url": "http://192.168.168.76:8080/HTMLPortingNewService/GetData?ChartName=widget3LineChart&lob=M&carrier=0&enrollmenttype=0&state=0&agent=0&fromdate=04%2F03%2F2015&todate=05%2F03%2F2015&requestID=499F6BF5E4610454A887AB37AF0814E8",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "ac20a050-a8c8-6d58-4350-66141d519394",
"content-type": "application/x-www-form-urlencoded"
},
"data": {
"username": "aHRtbHVzZXIx",
"password": "SHRtbDIwMTY="
}
}
$.ajax(settings).done(function (response) {
console.log(response);
decrypted = decryptByDES(response, keyString);
console.log(decrypted);
});
}
And in your HTML call this function:
<button onclick="callServer();">View</button>