Submitting HTTP request from HTML to AWS API gateway - html

I have a HTML form with a button which allows me to send HTTP requests in "text/plain" or "application/x-www-form-urlencoded" format.
text/plain:
stateMachineArn=arn:aws:states:us-east-1:0111111165:stateMachine:MyStateMachine
name=ExecutionName
first_name=test
last_name=test2
application/x-www-form-urlencoded:
stateMachineArn=arn:aws:states:us-east-1:0111111165:stateMachine:MyStateMachine&name=ExecutionName&first_name=test&last_name=test2
But AWS API gateway receives only JSON format by default ("input" has to be escaped)
{
"input": "{\"first_name\" : \"test\",\"last_name\" : \"test2\"}",
"name": "ExecutionName",
"stateMachineArn": "arn:aws:states:us-east-1:0111111165:stateMachine:MyStateMachine"
}
How can I convert either formats to the above JSON?

If you have a form like this:
<form>
<input type="stateMachineArn" name="stateMachineArn" id="stateMachineArn" />
<input type="name" name="name" id="name" />
<label for="first_name">First name</label>
<input type="first_name" name="first_name" id="first_name" />
<label for="last_name">Last name</label>
<input type="last_name" name="last_name" id="last_name" />
<button type="submit">Submit</button>
</form>
You can handle submissions in js like this and log the response like you did - don´t know if that´s what you are doing:
function handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
const value = Object.fromEntries(data.entries());
console.log({ value });
}
const form = document.querySelector('form');
form.addEventListener('submit', handleSubmit);
At this point if you want to convert data object to json before sending it somewhere or just to log it, have you tried this?
console.log(JSON.stringify(data));
Or this?
console.log(JSON.stringify(value ));
EDIT
To send the request:
$.ajax({
type: "POST",
url: "/webservices/PodcastService.asmx/CreateMarkers",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
error: function(errMsg) {
alert(errMsg);
}
});

Related

Autocomplete input suggestions

I'm trying to set up an input with autocomplete places list. I want to use Here autosuggest tool.
https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-autosuggest-brief.html
For this I did this code :
<div class="autocomplete input-group has-warning">
<input id="search-where" name="w" type="text" class="form-control input-lg" placeholder="A quel endroit?" required="required" value="" autocomplete="on" onkeyup="mySearch(this.value)" />
<span class="input-group-btn">
<button type="submit" class="btn btn-lg btn-warning"><span class="glyphicon glyphicon-screenshot"></span></button>
</span>
</div>
{literal}
<script type="text/javascript">
function mySearch(e){
$.ajax({
url: "https://places.ls.hereapi.com/places/v1/suggest",
type: 'GET',
data: {
at: '44.771079,5.742806',
q: 'savoie',
app_id: '2FXOZOY',
app_code: 'b_9sMKgQmSjWUj1rlyY0wI'
},
headers : { "Authorization": "Bearer" + $('b_9sMKgQ5qzJF0SusExJJx9irrHHimSjWUj1rlyY0wI').val()},
beforeSend: function(xhr){
xhr.setRequestHeader('Accept', 'application/json');
},
success: function (data) {
alert(JSON.stringify(data));
}
});
$( "#search-where" ).autocomplete({
source: mySearch
});
}
</script>
{/literal}
But I get this error when I try to write in the input :
I'm clearly completely lost ... If anyone can help me it would be much appreciated.
Thanks for reading me anyway
I think you are doing an XMLHttpRequest to a different URL than the page you are on. In such scenarios, browser blocks it completely giving CORS error due to security reasons. There are a lot of ways to set this. A tutorial is available here.

How to send data to HTML page and how to use AJAX for Single Page Application in NodeJS Server using express.js framework?

How can I display the form submitted data in another HTML Page
From 1st page (page1.html)collecting the data from users and after appending this data in the database I want to show the submitted values in another page i.e.(page4.html)
Below is my code
I have tried using res.sendFile or res.send
server.post('/addname', (req, res) => {
const user = {
timestamp: new Date,
FName: req.body.FName,
LName: req.body.LName,
Phone: req.body.Phone,
Email: req.body.email,
Contact: req.body.business,
Business: req.body.contact,
OTP: req.body.otp_field
}
res.sendFile(__dirname + '/page4.html');
//along with file rediraction, how can i send or show the "User" vaules in respactivte filed
});
<body>
<div>
<div align="center">
<form action="/addname" method="GET">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="submit" value="Submit" /></form>
</div>
</div>
</body>
nAs I can see in your code
<body>
<div>
<div align="center">
<form action="/addname" method="GET">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="submit" value="Submit" /></form>
</div>
</div>
</body>
Your form method is "GET", it should be "POST" as your API is "POST".
server.post('/addname', (req, res) => {
<form action="/addname" method="GET">
//Just change to
<form action="/addname" method="POST">
While sending and HTML file you need to send your submitted data too.
res.sendFile(__dirname + '/page4.html');
In order to save your hurdle switch to Single Page Application and use some JavaScript frame work like AngularJs, ReactJs or if not then also stick to single page and use Ajax calls for submit calls.
Else see "ejs" in place of "HTML" and use scriptlet to send and show data over HTML.
To send data to "ejs" via expressJs
res.render('show.ejs', {message});
With Ajax you can do this:
HTML
<body>
<div>
<div align="center">
<form id="form1">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="button" value="Submit" onClick:"submitForm()"/>
</form>
<div id="showValue"></div>
</div>
</div>
</body>
JavaScript
function submitForm() {
$.ajax({
url: '/addName',
type: 'POST',
headers: headers,
data: {
"Fname": $("#FName").val(),
"Lname": $("#LName").val(),
"email": $("#email").val()
},
success: function(result) {
//append result to your html
//Dynamic view
$("#form1").hide();
var html = '<div><span>First Name: ' + result.fName + '</span><span>Last Name: ' + result.lName + '</span></div>';
$("#showValue").html(html);
},
error: function (error) {
alert('error ',error);
}
});
}
Server side code I'm assuming you are using express.js and body-parser
app.post('/addName', (req, res) => {
//Insert into db
var body = req.body;
res.send({
fName: body.FName,
lName: body.LName
});
});

Where to add Content Type - application/JSON in html form? Error - Unable to decode JSON data

I need to pass json file to API but it looks like I need to do something to the JSON file before it send to the API. The error is "Unable to decode JSON data".
<form name="myform" enctype="multipart/form-data" action="https://api-106.dxi.eu/ecnow.php" method="POST" enctype='application/json'>
<input type="hidden" name="method" value="ecnow_records">
<input type="hidden" name="token" value="xxxxxxxxxxxxxxxxxxxxx">
<input type="hidden" name="action" value="create">
<input type="hidden" name="format" value="json">
<input type="hidden" name="raw" value="1">
Send this file: <input name="easycall" type="file">
<input type="submit" value="Send json File">
</form>
It works fine when I tried with Postman and pasted the JSON into Body->Raw. I am not sure where exactly the Body->Raw represent in HTML form?
Please advise.
Thank in advance
Finally, I get it working way. Thank for your helps.
$(document).ready(function(){
$.getJSON('dataset.json', function (data) {
$.ajax({
url: "https://xxxxxxxxxxxx",
xhrFields: 'withCredentials:true',
type: "POST",
data: JSON.stringify(data),
contentType: 'application/x-www-form-urlencoded',
success: function (data) {
alert("success"+data);
},
error: function (xhRequest, ErrorText, thrownError) {
alert("Failed to process correctly, please try again");
}
});
});

How Set Authorization headers at HTML Form or at A href

I have this code:
$.ajax({
url: "http://localhost:15797/api/values",
type: 'get',
contentType: 'application/json',
headers: {
"Authorization": "Bearer " + token
}
})
works fine, but I want to do that without using Ajax, I want something like that:
<form action="http://localhost:15797/api/values" method="get">
<input type="hidden" name="headers[Authorization]" value="Bearer token" />
<input type="submit" />
</form>
Is it possible? Or just do something like that without XMLHttpRequest? How?
You need to send the Authorization argument in the HTTP request header, it's imposed by OAuth flows. Of course you can change it by making changes in OAuth server's code but if you've got no control on the OAuth server's code it's not possible.
So answering your question, no you can't send them with the form's posted data. However, obviously you can put them in the hidden field and write a JS code to read it from the field and put it in the request header.
e.g.
HTML:
<input id="tokenField" type="hidden" />
<input id="submitButton" type="button" />
Javascript:
$('#submitButton').on('click',function(){
$.ajax({
url: "http://localhost:15797/api/values",
type: 'GET',
contentType: 'application/json',
headers: {
"Authorization": "Bearer " + $('#tokenField').val()
},
async: false
}});
Notice the async: false makes your call synchronous, just like a submit. And if you need to post other data to the server you can change the type: 'GET' to type: 'POST' and add another field named data and pass your form data through its value :
<input id="firstName" type="text" />
<input id="lastName" type="text" />
<input id="tokenField" type="hidden" />
<input id="submitButton" type="button" />
$('#submitButton').on('click',function(){
$.ajax({
url: "http://localhost:15797/api/values",
type: 'POST',
data: {
firstName: $('#firstName').val(),
lastName: $('#lastName').val()
},
contentType: 'application/json',
headers: {
"Authorization": "Bearer " + $('#tokenField').val()
},
async: false
})
});

Send JSON from HTML form with NODEJS backend

I haven't done front end HTML since I was 10 and that was drag and drop frontpage stuff. with static pages. As a result I'm really rusty.
What I need to do is put together a web client for a rest API that I wrote in NodeJS. My question is how, do you send a request from a form (say a log in form) to the server where the body of the POST request is a JSON of the email/password?
HTML form:
<form id="loginForm" action="" method="" class="form-horizontal">
<fieldset>
<legend>Log in</legend>
<div class="control-group">
<label class="control-label" for="email">Email</label>
<div class="controls">
<input type="text" class="input-xlarge" id="email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" class="input-xlarge" id="password">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Save changes</button>
<button class="btn">Cancel</button>
</div>
</fieldset>
</form>
I suggest a lot of reading. To get you started with a very basic example, though, you will find a page with a sample form below that does what you need. You just need to replace the string your URL here with the actual URL you expect will be doing the handling.
The serializeObject() function was taken from here: Convert form data to JavaScript object with jQuery
<html>
<body>
<form id="loginForm" action="" method="">
Username: <input type="text" name="username" id="username" /> <br />
Password: <input type="password" name="password" id="password" /> <br />
<input type="submit" />
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function () {
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("#loginForm").bind("submit", function(evt) {
console.log(JSON.stringify($("#loginForm").serializeObject()));
$.ajax({
url: "your URL here",
type: "POST",
contentType: "application/json",
data: JSON.stringify($("#loginForm").serializeObject()),
success: function (data, textStatus, jqXHR) {
// do something with your data here.
},
error: function (jqXHR, textStatus, errorThrown) {
// likewise do something with your error here.
}
});
return false;
});
});
</script>
</body>
</html>
The problem with your form is that input elements don't have name attributes. The name attribute is essential in many ways, so I would fix your html by setting each element's name attribute to the same value as its id attribute. The serializeObject function relies on form elements having names.
Here's an example using jQuery:
<form name="myform" action="#" method="POST">
Username: <input type="text" id="user" name="username"/><br/>
Password: <input type="password" id="pass" name="password"/>
<input type="submit" id="login" value="Login"/>
</form>
<script type="text/javascript">
var user=$('#user').val(), pass=$('#pass').val();
$('login').bind('click', function() {
$.ajax('/my/url', {
type: 'POST',
contentType: 'text/json',
data: JSON.stringify({username:user, password:pass}),
complete: function() { /* Do something with the response. */ }
});
return false; // Prevent form submit.
});
</script>
This might help you. Here is the form below: If you notice there is action and method if you don't know what these are, just go on and search for it. Action is the target server file that handles the information you send and method is get which is retrieving not updating.
Existing Users Username: Password:
Keep Me
Logged In
Here is the jquery part to handle the ajax call:
$.ajax({
type: "GET",
url: action,
data: form_data,
success: function(response)
{
if($.trim(response) == 'success')
window.location.replace("profile.php");
else
$("#result").html(response);
}
});
return false; });
});