AJAX return from SmartyStreets API - html

I am having trouble actually returning any kind of object using this AJAX call. I know I am doing something wrong, but I have no idea where. I hope someone can help me I am looking to return an element in the object "zip". I would like to have any response really, but I can not get anything back.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var result = $('#resultDiv')
$.ajax({
url: 'https://us-street.api.smartystreets.com/street-address',
method: 'get',
data: {
auth-id='your-auth-id',
auth-token='your-auth-token',
street=$('#street'),
city=$('#city'),
state=$('#state')
},
dataType: 'json',
success: function(data) {
if (data = null)
{
result.html('You failed');
}
else {
result.html('Match:' + data.components[0].zipcode)
}
}
});
});
});
</script>
<title>SSTest</title>
</head>
<body>
<div class="container">
<h1 style="text-align:center"> Welcome to Address Check </h1>
<form action="#" method="post">
<div class="form-group">
<label for="street">Street</label>
<input type="text" id="street" class="form-control" name="street">
</div>
<div class="form-group">
<label for="city">City</label>
<input type="text" id="city" class="form-control" name="city">
</div>
<div class="form-group">
<label for="state">State</label>
<input type="text" id="state" class="form-control" name="state">
</div>
<button type="submit" id="submit" class="btn btn-default">Submit</button>
<br/>
<br/>
<div id="resultDiv"></div>
</body>
</html>

As you are using a GET call, you can test this in the browser first AND make sure you are getting a response before you start wrapping it in a JQuery call.
https://us-street.api.smartystreets.com/street-address?auth-id=[your-auth-id]&auth-token=[your-auth-token]&street=SOMETHING&state=SOMETHING&city=SOMETHING
If you get a non-result, then consult the API to see if you are passing the correct parameters.
Using the DOCS, this call returns data for your API Keys -
https://us-street.api.smartystreets.com/street-address?auth-id=[your-auth-id]&auth-token=[your-auth-token]&street=1600+amphitheatre+pkwy&city=mountain+view&state=CA&candidates=10
This JQuery Get HTML example gets a response -
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("https://us-street.api.smartystreets.com/street-address?auth-id=[your-auth-id]&auth-token=[your-auth-token]&street=1600+amphitheatre+pkwy&city=mountain+view&state=CA&candidates=10", function(data, status){
alert("zipcode: " + JSON.stringify(data));
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
You should be able to build from that as you refine your JQuery understanding to get exactly what you need.

I was able to find a handful of errors with your code and fixed them here in this JSFiddle. Here are the list of errors you had.
Don't include your auth-id, auth-token in public code. You're giving away your address lookups by doing this. You should go remove these from your account and generate new ones.
In your original success function you didn't do a compare. You should use == here. Actually, the API will never send back null for data on success so you don't even need this here anymore. Use the error function instead.
The data object passed in the ajax call is done incorrectly. You should not be using =, instead use :.
In the data object you should call .val() after the jQuery selectors to get the values entered into those fields.
data.components[0].zipcode should be data[0].components.zipcode. The api will return back a data array of objects. components is not an array.

The auth-id and token should only be used when used from server side.
It is clearly mentioned not to expose the auth-id and auth-token in the documentation.
I used the FETCH API from Javascript and the code looks like this:
var key = '' //your embedded key here
var street = encodeURIComponent('1600 amphitheatre pkwy');
var city = encodeURIComponent('mountain view');
var state = 'CA';
var url = 'https://us-street.api.smartystreets.com/street-address?street=' + street + '&city=' + city + '&state=' + state + '&key=' + key;
const response = await fetch(url)
const responseData = await response.json()

Related

Send POST JSON Data and Receive With Node.js (NO BODYPARSER)

I'm frustrated because I can't send from HTML or receive from Node.js JSON data. I think that I'm near to resolve, but I'm tired trying for hours. Anybody helps me?
As the code below, the responde is null (req.body = null?) in my VSCODE.
When I try from Insomnia, that's ok. When I try from HTML Form, fails. *
I could to use BodyParser, but why to send from Insomnia works and from HTML Form doesn't?
//routes.js
routes.post('/go', (req, res) => {
console.log(req.body)
return res.json({ "Response": req.body })
})
<!DOCTYPE html>
<html>
<head>
<title>API Correios</title>
</head>
<body>
<form id="FrmQuery" action="http://localhost:3333/go" method="POST" enctype="application/json">
<label for="sCepOrigem">Cep Origem</label><br>
<input type="text" name="sCepOrigem" id="sCepOrigem"><br><br><br>
<input type="text" id="jsonData"><br><br>
<button id="send" type="button">Enviar</button>
</form>
<script>
document.querySelector('#send').addEventListener('click', (event) => {
let sCepOrigem = document.querySelector('#sCepOrigem')
var obj = {
"sCepOrigem": sCepOrigem.value,
};
var myJSON = JSON.stringify(obj);
document.querySelector('#jsonData').value = myJSON
document.querySelector('#FrmQuery').submit()
})
</script>
</body>
</html>
In Javascript from web browser you need to send it as raw XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Other possibilities would be jQuery's $.ajax or maybe the new fetch API.
Based on my experience with node js, I believe you have to simply res.send and cut out the return statement.
Hope this helps.

Send a form without the "?" character and the name of the value

I have this code:
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form action="https://api.pagar.me/1/zipcodes/">
<input type="text" placeholder="cep" name="cep">
<input type="submit">
</form>
</body>
</html>
When I type a number, for example 05423110, I get on the adress bar is "https://api.pagar.me/1/zipcodes/?cep=05423110", but I would like to have "https://api.pagar.me/1/zipcodes/05423110".
What do I need to change on my code?
Thanks!
I would do it like this. The other answer will have the problem where it could potentially append something twice.
I also set it so the button disables for user friendliness (in case the server takes awhile to respond).
This solution does use jQuery, but chances are you will need to do other simple DOM manipulation and this will be very helpful.
Because you don't want the query string in there, but you must have it be GET, then its impossible not to have it append the query string to the URL (because that's what a GET request does).
Instead, I use javascript to simply redirect to the proper URL and ignore the form GET/POST entirely.
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form action="https://api.pagar.me/1/zipcodes/">
<input type="text" placeholder="cep" name="cep">
<input type="submit">
</form>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
(function() {
var form = $('form');
var baseUrl = form.attr('action');
$('form').submit(function(e) {
e.preventDefault();
form.find('[type="submit"]').prop('disabled', true);
window.location.href = baseUrl + form.find('[name="cep"]').val();
});
})();
</script>
Add method="post" to the form tag, then add an event listener to the form's submit event which append the input value to the action attribute value on the form:
const form = document.forms[0]
form.addEventListener('submit',()=>{form.action+=cep.value})
<form action="https://api.pagar.me/1/zipcodes/" method="post">
<input type="text" placeholder="cep" name="cep" id="cep">
<input type="submit">
</form>
Ofc StackOverflow snippets prevents POST.

How can i get response coming from web server

i have a form, i am asking customer to enter few details,
<form id="redirectForm" accept-charset="UTF-8" method="post" action="https://test.test.com//api/v1/order/create" >
customerName: <input type="text" name="customerName" value=<%=customerName %> />
customerEmail: <input type="text" name="customerEmail" value=<%=customerEmail %> /><br><br>
customerPhone: <input type="text" name="customerPhone" value=<%=customerPhone %> /><br><br>
signature:<input type="text" name="signature" value=<%=signature %> />
On submit page redirect according to action of form and display a JSON type response(status + payment link).
response is like:
{"status":"OK","paymentLink":"https:\/\/test.test.com\/billpay\/order\/3ackwtoyn7oks4416fomn"}
Help me out with this
i am working in jsp.
thank you in advance.
Since this look like a simple Webservice answer (not a full HTML page), I would use Ajax to send the form and manage the response.
With JQuery, this is easy using $.ajax
$.ajax({
url: //the URL
data: //the form value
method: //GET/POST
success: function(response){
//decode the JSON response...
var url = $.parseJSON(response).paymentLink;
//then redirect / not sure since this could be cross-domain...
window.loacation = url;
},
error: function(error){
...
}
})
The only think is that the form should not be send with a submit input, you need to link a button to a function doing this Ajax call.
This can be done without JQuery but I can write this from memory ;)
If you can edit the JSP creating the response, you could generate an HTML to return the value directly.
<html>
<head>
<script>
window.location.href = '${paymentLink}';
</script>
</head>
<body>
Redirection ...
<br>If nothing happend, you can <a href='${paymentLink}'>click here</a> to be redirected.
</body>
</html>
Where ${paymentLink} is a EL that will print the value of this variable (well the name it has on the server) to complete the script with the URL.
Once it is received by the client, it will be executed.
Of course, this will not be cross-domain on every browser. If this is not, you will need to provide the link to the user with <a href='${paymentLink}'>Redirection</a> itsefl.
Try this...
while submitting the form write one JS function and get the URL value.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function check(){
//here you have to get value using element name or id (val1,val2,val3)
$.ajax({
type:'GET',
data: {customerName: val1, customerEmail: val2,customerPhone: val3},
url:'https://test.test.com/billpay/order/3ackwtoyn7oks4416fomn',// Replace with Your Exact URL
success: function(response){
alert(response);
var json = JSON.parse(response);
var values = json.values;
for(var i in values)
{
var New_redirect = values[i].address;
alert(values[i].address);
}
window.loacation=New_redirect;
}
});
})
}
</script>
</head>
i think you are looking for response message and redirecting to somewhere
if so you can use the following code
if(condition)
{
response.sendRedirect("urpage.jsp");
}
or
if(condition)
{
request.getRequestDispacher("page.jsp");//enter the name of page you want to redirect inside ""
}

Connecting Node.JS to HTML Form

I am new to node.js and I'm trying to create an easy way for a user to input data into an html form, then on the click of submit the data is passed to a node.js script. The node.js script is a post script that takes the user's inputed data and then makes a post to a API and takes a return in JSON from the API. I am trying to get the returned JSON to be printed back onto the html page. How do you do this in a clean and easy manner?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Commute | Ad-hoc</title>
<link rel="stylesheet" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="container cf">
<div class="container cf">
<div>
<h1>Manual Query</h1>
<label>Mode</label>
<select id="modes">
<option value="driving">Driving</option>
<option value="walking">Walking</option>
<option value="cycling">Cycling</option>
</select>
<label>Latitude Origin</label>
<input type="text" name="latitude_origin" id="latitude_origin" value="37.791871">
<label>Longitude Origin</label>
<input type="text" name="longitude_origin" id="longitude_origin" value = "-122.396742">
<label>Latitude Destination</label>
<input type="text" name="latitude_dest" id="latitude_dest" value = "37.782461">
<label>Longitude Destination</label>
<input type="text" name="longitude_dest" id="longitude_dest" value = "-122.454807">
<button id="singleQuery" class="singleQuery" input type="default small">Run</button>
</div>
<div>
<h1>Multi-Query (.tsv)</h1>
<label>Upload</label>
<input type="file" name="pic" id="laserPrinters">
<button id="testLaser" class="default small" input type="default small">Run</button>
</div>
<div>
<h1>Result</h1>
<textarea rows="4" cols="50"> </textarea>
</body>
</html>
<script type="text/javascript">
var mode = $("#modes").val();
var latitude_origin = $("#latitude_origin").val();
var longitude_origin = $("#longitude_origin").val();
var latitude_dest = $("#latitude_dest").val();
var longitude_dest = $("#longitude_dest").val();
</script>
My Node.JS post script:
var request = require("request");
var options = { method: 'POST',
url: 'http://blah:8000/blah/blah/blah/blah/[latitude_origin]/[longitude_origin]/',
headers:
{ 'postman-token': 'blah',
'cache-control': 'no-cache' },
body: '{"query1":[latitude_dest,longitude_dest]}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
First, you have to setup a server to listen to the requests that you will send to your node.js web api.
I really like recommend you use express.js. It is a very powerful web server.
Read more in:
https://expressjs.com/
I am writing some example for you soon.
Hope it help you.
UPDATE 1
Take a look at MEAN Stack
https://github.com/meanjs/mean
UPDATE 2
Here are some examples:
https://scotch.io/tutorials/setting-up-a-mean-stack-single-page-application
https://developers.openshift.com/languages/nodejs/example-meanstack.html

Sending form data to spring controller using dojo

I've a list of records and want to update one. When I click on one, it show a form with all input fields which are already populated using JsonRest. I've edited the fields and now I want to send it to server for updating.
How can I send an Object with dojo?
I tried like this, but at the controller side the value is null.
on(dom.byId("poolForm"), "submit", function(evt) {
var formObj = domForm.toObject("poolForm");
console.log(formObj);
request.post("/path/to/EditSubmit", {
data : formObj,
method : "POST"
}). then(function(data) {
console.log("data");
});
});
In spring I used:
public void editedForm(HttpServletResponse response, #RequestBody MyClass myClass) {
poolParam.getAdd();
}
Assuming you are creating a new record and not updating one, you can use method add(object, options) for your JsonRest.
Example:
require(["dojo/store/JsonRest"], function(JsonRest){
// your store
var store = new JsonRest({
target: "/some/resource"
});
// add an object passing an id
store.add({
foo: "foo"
}, {
id: 1
});
});
More informations can be found at JsonRest API and JsonRest guide.
EDIT:
As for your comment request, in case you would like to send an object using dojo/request/xhr instead of JsonRest, you can use the following example, basically:
Use dojo/dom-form utility, to get out values from your form. This utility function will return an object. More info here.
Use dojo/request/xhr to send via Ajax the object previously retrieved from dojo/dom-form, this is the data sent to the server. More info here.
Quick demo here:
https://jsbin.com/mocoxuhotu/edit?html,output
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/dojo/1.10.0/dijit/themes/claro/claro.css">
<script data-dojo-config="async: 1" src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<script>
require([
"dojo/query",
"dojo/dom-form",
"dojo/request/xhr",
"dijit/registry",
"dijit/form/Form",
"dojo/parser",
"dojo/domReady!"
], function (
query,
domForm,
xhr,
registry,
Form,
parser
) {
var form = new Form({}, 'myForm');
query("a.myLink").on("click", function () {
var data = domForm.toObject(form.domNode);
xhr.post("/echo/json", {
data: data // data to transfer
}).then(function () {
console.log("Success");
});
});
});
</script>
</head>
<body class="claro">
<form data-dojo-type="dijit/form/Form" id="myForm">
<fieldset>
<ul>
<li>
<label for="name">Name:</label>
<input type="text" name="name" />
</li>
<li>
<label for="firstname">First name:</label>
<input type="text" name="firstname" />
</li>
</ul>
</fieldset>
</form>
<a class="myLink">Submit the form</a>
</body>
</html>