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.
Related
I want to use form input from HTML to JS. For that i am using following snippet but getting "SyntaxError: Unexpected token if" can anyone help in modifying it.
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function(req, res) {
fs.readFile(html_form_path, function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
var q = url.parse(req.url, true);
var qdata = q.query;
res.write(qdata.Input());
}).listen(8080);
HTML FORM:
<html>
<body>
<form type='get'>
<input type="text" name='Input'>
<input type='submit'>
</form>
</body>
</html>
You should send data from html to server, you will need bodyparser and it is easiest to do if you also have express on server then you make submit button and i form tag add action and method atributes and on server you expect
app.post("/action",function(req,res){
req.body.input
})
html:
<form action='/action' method='POST' >
<input name=input''>
<input type='submit'>
</form>
also this will reload your page, if you want not to reload you need use ajax to send data you can use axios in javascript.
see express docs on how to set it up and you need see bodyparser docs and then use this code
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()
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 ""
}
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>
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.