How can i get response coming from web server - json

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 ""
}

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.

Link or button that sends a POST but does not navigate

I need an anchor tag or button that sends a POST to a URL but doesn't navigate to anywhere.
This might not comply with current standards, but it works in Chrome.
<!DOCTYPE html>
<iframe style="display:none;" name="some"></iframe>
<form method="POST" target="some">
<button class="btn" style="margin:0px 10px 15px 0px;" type="submit"
formaction="http://www.example.org:1234/test?P1=X">Test</button>
</form>
In order to post the data without navigating to another page or refreshing the same page, you need to use Ajax.
From your code, I assume you are using jQuery. In jQuery, there are functions that allow to implement Ajax easily.
I will add a sample code below for your reference.
$("#myLink").click(function(event) {
event.preventDefault();
var url = "http://example.com"; //The url/uri where you want to post the data to
var data = {field1: "data1", field2: "data2"}; //Your data
$.post(url, data, function(data, status) {
//Data and status from server after posting your data
console.log(data);
console.log(status);
});
});
And your a tag will remain the same.
Send

Show validation message without using required

I want to display a validation message only when a user types something in the input field. I can't put required in the input box.
<input type="url" class="form-control" name="website_url">
The input data should be a valid website URL.
Can I do this without using Jquery or Javascript?
You can achieve this by javascript like this.
<!DOCTYPE html>
<html>
<body>
Enter your url: <input type="text" id="url" onfocusout="myFunction()">
<script>
function myFunction() {
var x = document.getElementById("url");
var re = //use valid regex here;
if (!re.test(url)) {
alert("url error");
return false;
}
}
</script>
</body>
</html>
you have to use valid regex for url like this
but I prefer to do server side validation to in case javascript is off.

AJAX return from SmartyStreets API

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()

How to send JSON object/string (as 'POST') to a webservice using $resource in angularjs

I'm an absolute newbie in angularjs and don't have any idea about web services either.
My requirement is something like this:
I'll have a basic login page (to be designed using html and angularjs) which is going to ask for my credentials (Username and Password). On providing a set of credentials and clicking on the "Submit" button, my code needs to process the form data and pass the information on to a webservice. I just have the url of the webservice with me and nothing else.
Thus my principal objective would be to send across the username and password to the webservice (preferably as a JSON object) and check whether its working properly or not. So far, I've successfully managed to:
1> Hit the webservice (I've used $resource for doing the same.)
2> Store the username and password as a JSON object.
Now I need to accomplish two things:
1> send this data as "POST" and most importantly, 2> send this JSON data(as an object or string) to the webservice.
I'm absolutely clueless...Please help me out by modifying my code.
Thanks in advance. Here's my JS file:
var app = angular.module('angularjs-starter', ['ngResource']);
app.controller('MainCtrl', function ($scope,$http,$resource) {
$http.defaults.useXDomain = true;
$scope.checkUsername = function(){
var USERNAME = $scope.inputUsername;
var PASSWORD = $scope.inputPassword;
var f = JSON.stringify({USERNAME: USERNAME, PASSWORD: PASSWORD });
var result= JSON.parse(f);
var Something = $resource("/some url/:id", {id: "#id"},
{
post:{
method:"POST",
isArray:false
},
});
$scope.something = Something.get({id:1});
$scope.alertMessage = "Web service has been successfully hit!";
};
});
And here's my HTML file:
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8">
<title>Authentication</title>
<script src="C:\Users\Rup\Desktop\POC2\js\angular.js"></script>
<script src="C:\Users\Rup\Desktop\POC2\js\angular-resource.js"></script>
<script src="C:\Users\Rup\Desktop\POC2\experiment_2.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body ng-controller="MainCtrl">
<h1>Hello</h1>
<form name="form1" class="form-horizontal">
<label class="control-label" for="inputUsername">Username</label> <input
type="text" id="inputUsername" placeholder="Username"
ng-model="inputUsername"> <br /> <label
class="control-label" for="inputPassword">Password</label> <input
type="password" id="inputPassword" placeholder="Password"
ng-model="inputPassword"> <br /> <span class="help-block">{{alertMessage}}</span>
<br />
<!--<a class="btn">Sign in</a>-->
<button ng-click="checkUsername()">Submit</button>
</form>
</body>
</html>
The good news is that this should be fairly straight forward. You have the right idea, you just need to extend the resource object as you have done with "post" method, and when you call it - pass in your JSON object. Angular will then append the passed in JSON object as post parameters automatically. It's a good idea (I've read), to create this User resource as a service/factory so that you can inject it into your controllers to abstract the calls to the server. As an example - something I have done would be to create the service like so (with a dependency on the angular $resource):
var myApp = angualar.module('myApp', []);
myApp.factory('UserService', ["$resource",
function UserService($resource) {
var UserService = $resource('/rest/user', {}, {
search: {
method: 'POST',
url: window.location.origin +'/yourServer/rest/search' //custom url of your service to be called
}
});
return UserService;
}
])
Then in your controller, you inject the service to be used, and create a method that then calls your shiny new service:
myApp.controller("myAppController", ["$scope", "UserService",
function myAppCtrl($scope, UserService) {
$scope.search = function () {
var params = {
param1: "searchValue1",
param2: "searchValue2"
}
var response = UserService.search(params);
response.$promise.then(
function success() {
//celebrate!
},
function fail(err) {
//comiserate
}
);
}
}
The response object from the call to the service method is a promise, which you attach your success or fail functions to be called when the call successfully returns or fails.