Form data to accept nested schema in Javascript - html

I have a JSON schema which i am trying to make my form tailor, but the schema has nested objects and arrays like so:
{
"person": {
"firstName":"Kay",
"lastName":"Young"
}
"addressDetails":[
{
"line1": "line1",
"line2": "line2"
}]
}
HTML
<div class="form-group">
<label for="caseIdentifier">First Name</label>
<input type="text" class="form-control" id="firstname" name="?">
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" class="form-control" id="lastName" name="?">
</div>
<div class="form-group">
<label for="line1">Line 1</label>
<input type="text" class="form-control" id="line1" name="?">
</div>
<div class="form-group">
<label for="line2">Line 2</label>
<input type="text" class="form-control" id="line2" name="?">
</div>
JS
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function (e) {
e.preventDefault();
const url = url;
const formData = new FormData(this);
let object = {};
formData.forEach(function (value, key) {
object[key] = value;
});
let json = JSON.stringify(object);
let fetchData = {
method: 'POST',
body: json,
headers: <myHeaders>
}
fetch(url, fetchData)
.then(function (response) {
console.log(fetchData)
return response.text();
}).then(function (text) {
console.log(text);
}).catch(function (error) {
console.error(error);
});
});
How do I tailor my HTML form to match these parameters in JS? please.
....................................................................................................................................................................................................................................................................................................................................................................................................................................................................

Related

How to Pass JSON data inside HTML attributes

I have created a form using HTML and trying to pass the value of a JSON object in the HTML attribute. I have used fetch to get the data from the api and used it to create options in my page that is made using vueJS. The problem is, the value that gets logged in the database is {{item}} instead of the value in the item.
How to resolve this issue?
AddLog.vue code:
<template>
<h1 style="margin-top: 107px; text-align: center;color: ;">Log the values into the tracker</h1>
<form #submit.prevent="submit" style="margin-right: 522px;margin-top: 29px; margin-left: 519px" method="POST">
<div class="form-group">
<label for="exampleInputEmail1" required style="color: ;">Note</label>
<input type="name" class="form-control" v-model="data.note" id="exampleInputEmail1" aria-describedby="emailHelp" name="Note" placeholder="Note" style="border-radius: 20px;">
</div>
<div class="form-group" v-if="this.trackertype==='Numerical'" >
<label for="exampleInputPassword1" required style="color: ;">Enter the Value</label>
<input type="value" class="form-control" v-model="data.value" id="exampleInputPassword1" name="value" placeholder="Value" style="border-radius: 20px;" required>
</div>
<div class="multiple-choice" v-else>
<label for="value" style="color: ;">Check the value</label>
<div class="form-check">
<div v-for="item,index in this.trackersettings" :key="index">
<input type="radio" name="value" v-model="data.value" value="{{item}}" required>
<label>{{item}}</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-outline-dark" style="border-radius: 15px;">submit</button>
</form>
</template>
<script>
import { reactive } from 'vue';
import axios from 'axios';
export default {
Name: 'AddLog',
data(){
return{
uid : this.$route.params.uid,
tid : this.$route.params.tid,
items : [],
trackertype: '',
trackersettings: []
}
},
mounted() {
localStorage.setItem('uid',this.uid)
localStorage.setItem('tid',this.tid)
axios.get('http://localhost:5000/addLog/'+this.uid+'/'+this.tid)
.then((resp ) => {
this.items = resp.data
this.trackertype = this.items[0]['data']['trackertype']
this.trackersettings =this.items[1]['tracker_settings']
console.log(this.trackertype,this.trackersettings)
})
.catch((err) => {
console.log(err.resp)
})
},
setup() {
const data = reactive({
note: '',
value: ''
})
const submit = async () => {
await fetch("http://localhost:5000/addLog/"+localStorage['uid']+'/'+localStorage['tid'],{
method: 'POST',
headers: {'Content-Type' : 'application/json','Access-Control-Allow-Origin': '*'},
body: JSON.stringify(data)
}).then(resp => resp.json())
.then(data => {console.log(data);})
.catch(error => { console.log(error)
})
}
return {
data,
submit,
}
}
}
</script>
<style>
</style>
API code:
#app.route('/addLog/<int:uid>/<int:tid>', methods=['GET', 'POST'])
def log(uid,tid):
cell = tracker.query.filter_by(u_id=uid,tracker_id=tid).first()
l = cell.tracker_settings.split(',')
d = {
'userid' : cell.u_id,
'trackerid' : cell.tracker_id,
'trackername' : cell.tracker_name,
'trackerdesc' : cell.tracker_description,
'trackertype' : cell.tracker_type,
'tracker_settings' : cell.tracker_settings,
'datecreated' : cell.date_created
}
if request.method=='POST':
data = request.json
val = data['value']
note = data['note']
cell = logtable(user_id=uid,t_id=tid,Note=note,value=val)
db.session.add(cell)
db.session.commit()
return jsonify({'message':'success'})
else:
return jsonify({'data':d},{'tracker_settings' : l })
I want the values in the options to be logged in the db.
Instead of the "{{item}}" in the value , I need the string "Gloomy". Can Anybody help me on doing this?
Here is the correct way to assign the value :
Try :value="item" instead of value="{{item}}"
Demo :
var app = new Vue({
el: '#app',
data: {
selected: '',
item1: 'Male',
item2: 'Female'
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h2>Binding Radio</h2>
<input type="radio" id="one" :value="item1" v-model="selected">
<label for="one">Male</label>
<br>
<input type="radio" id="two" :value="item2" v-model="selected">
<label for="two">Female</label>
<br>
<span>Picked: {{ selected }}</span>
</div>

How to send nested json objects to the controller by using ajax

What I am trying to do is passing nested json objects to the controller
from where I have to set the field of those entity respectively. I have two entity named UserData and Address and I want to get nested objects for both the entity as the project requires.
As you can see at this phase I don't understand how to tackle this problem. help me out of this problem.
/front end/
<body>
<div class="container">
<div class="jumbotron">
<h1>File upload Demo</h1>
<p>File upload Demo along with the JSON data</p>
</div>
</div>
<div class="container">
<div class="alert alert-success">File uploaded successfully</div>
<div class="alert alert-danger">File is not uploaded. Error occurred</div>
<div class="form-group">
<label for="firstname">First Name:</label> <input type="text"
class="form-control" id="firstname" name="firstname">
</div>
<div class="form-group">
<label for="lastname">Last Name:</label> <input type="text"
class="form-control" id="lastname" name="lastname">
</div>
<div class="form-group">
<label for="state">State:</label> <input type="text"
class="form-control" id="state" name="state">
</div>
<div class="form-group">
<label for="city">City:</label> <input type="text"
class="form-control" id="city" name="city">
</div>
<form id="fileUploadForm">
<div class="form-group">
<input type="file" class="form-control-file border" name="file">
</div>
</form>
<button type="button" id="btnSubmit" class="btn btn-primary">Submit</button>
</div>
<script>
$(document).ready(function () {
$(".alert-success").hide();
$(".alert-danger").hide();
$("#btnSubmit").click(function () {
alert("hello");
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
var jsonDataObj = {
"firstname": $("#firstname").val(),
"lastname" : $("#lastname").val(),
"address" :{
"state": $("#state").val(),
"city" : $("#city").val()
}
};
data.append("jsondata", JSON.stringify(jsonDataObj));
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/upload",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
$(".alert-success").show();
$(".alert-danger").hide();
},
error: function (e) {
$(".alert-success").hide();
$(".alert-danger").show();
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
});
});
</script>
</body>
/**controller**/
#Controller
public class FileUploadRestController {
#Autowired UserRepo userRepo;
#Autowired uploadrep upld;
ObjectMapper objectMapper = new ObjectMapper();
ObjectMapper addressmap = new ObjectMapper();
#RequestMapping(value="/upload", method=RequestMethod.POST)
public ResponseEntity<Object> uploadFile(#RequestParam(required=true, value="file") MultipartFile file, #RequestParam(required=true, value="jsondata")String jsondata) throws IOException, ParseException {
System.out.println("file name is "+file.getOriginalFilename());
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(jsondata);
//System.out.println(json.getString("firstname"));
/*File convertFile = new File("c://mydownloads//"+file.getOriginalFilename());
convertFile.createNewFile();
FileOutputStream fout = new FileOutputStream(convertFile);
fout.write(file.getBytes());
fout.close();*/
System.out.println("data ies "+json);
//UserData personData = objectMapper.readValue(jsondata, UserData.class);
//Address addressData = addressmap.readValue(jsondata, Address.class);
//Address address =new Address(addressData.getState(),addressData.getCity());
/*UserData userData=new UserData(StringUtils.cleanPath(file.getOriginalFilename()),file.getContentType(),file.getBytes(),personData.getFirstname(),personData.getLastname());
System.out.println("uploaded datafiles ");
//String str=Base64.getEncoder().encodeToString(file.getBytes());
userData.setAddress(address);
userRepo.save(userData);*/
return new ResponseEntity<>("File is uploaded successfully", HttpStatus.OK);
}

Store null values in database while trying to save data using spring mvc angular js

angular js code
<body data-ng-app="myApp" data-ng-controller="UserController as userBean">
<form method="post" action="register" name="myForm">
<div class="form-group col-lg-7" >
<label for="username" class="control-label">First Name:</label>
<input type="text" data-ng-model="userBean.username" class="form-control" placeholder="Enter Firstname"/><br>
<label for="phone" class="control-label">Phone:</label>
<input type="text" data-ng-model="userBean.phone" class="form-control" placeholder="Enter phone no."/><br>
<label for="email" class="control-label">Email:</label>
<input type="text" data-ng-model="userBean.email" class="form-control" placeholder="Enter email"/><br>
<label for="address" class="control-label">Address:</label>
<input type="text" data-ng-model="userBean.address" class="form-control" placeholder="Enter address"/><br>
<label for="password" class="control-label">Password:</label>
<input type="password" data-ng-model="userBean.password" class="form-control" placeholder="Enter password"/><br>
</div>
<div class="form-group col-lg-7">
<button type="submit" data-ng-click="insertData()" class="btn btn-primary">Submit</button>
</div>
</form>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller("UserController", ['$scope', '$http', function($scope, $http, httpPostService) {
var self=this;
$scope.insertData = function()
{
alert($scope.userBean.username, $scope.userBean.phone, $scope.userBean.email);
$http({
method: "POST",
url: "register",
data:{
username: $scope.userBean.username,
phone: $scope.userBean.phone,
email: $scope.userBean.email,
address: $scope.userBean.address,
password: $scope.userBean.password}
}).then(function(response){
console.log(response.status);
console.log("in success");
}, function(response){
console.log(response.status);
console.log("in fail");
});
};
}]);
</script>
controller code
#RequestMapping(value="/register", method = RequestMethod.POST, consumes="application/json")
public #ResponseBody ModelAndView doRegister(#ModelAttribute #RequestBody UserBean userBean, BindingResult result)
{
if(!result.hasFieldErrors())
{
if(retrieveService.insert(userBean) != null)
{
System.out.println("done");
}
}
return new ModelAndView("redirect:/welcome");
}
}
I think a controller problem. userBean has null values to pass it to a controller. so kindly anyone helps me
It error also came
HTTP Status 415 – Unsupported Media Type The origin server is refusing to service the request because the payload is in a format not
supported by this method on the target resource.
Set content type JSON in your request headers like below.
$http({
method: "POST",
url: "register",
data:{
username: $scope.userBean.username,
phone: $scope.userBean.phone,
email: $scope.userBean.email,
address: $scope.userBean.address,
password: $scope.userBean.password},
headers: {'Content-Type': 'application/json'}
})
Use #JsonIgnore on the field which can have null values.

I am unable to render the JSON object that is being displayed as the response

The Previous issue of getting status 400 error has been resolved , I am able to retrieve the response as a JSON Object , I am here with attaching the modified code , The received JSON response is being stored in the JSON Object :
response_jsonObj , The output is in this format
0: { id: "value od id", name: "value of name" , field1: "value of field1" , field2: "value of field2" , ...}
0: { id: "value od id", name: "value of name" , field1: "value of field1" , field2: "value of field2" , ...} and so forth, I need to display this in the tabular format , I have followed the examples on stack overflow and am unable to replicate it , Any inputs are welcome .
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
this.state = { responsedata:[{"id":"","name":"","field1":"","field2":""}] }
}
handleSubmit(event) {
event.preventDefault();
const form = event.target;
const data = new FormData(form);
const arrayValue = [];
var i = 0;
console.log('Data from Form:',data);
for (let name of data.keys()) {
const input = form.elements[name];
const parserName = input.dataset.parse;
const parsedValue = data.get(name);
console.log('name',name);
console.log('parsedValue',parsedValue);
data.set(name, parsedValue);
arrayValue[i] = parsedValue;
i=i+1;
}
console.log('id:after get',arrayValue[0]);
console.log('field1:after get',arrayValue[2]);
console.log('field7:after get',arrayValue[8]);
var response_data = "";
var response_jsonObj ;
var txt = "";
var req = {"CustomerLookupRequest" : [{
"id":arrayValue[0],
"name": "",
"field1":arrayValue[2],
"field2":"",
"field3":"",
"field4":"",
"field5":"",
"field6":"",
"field7":arrayValue[8],
"field8":"",
"field9":"",
"fied10":"",
"field11":""
}]
};
console.log('req string :' + req);
fetch('API_URL', {
headers: {
'Accept': 'application/json, text/plain, application/xml, */*',
'Content-Type': 'application/json' ,
'Access-Control-Allow-Headers': 'Content-Type',
},
method: 'POST',
body: JSON.stringify(req)}
).then(function(response) {
if (response.status !== 200) {
console.log('Problem in fetching');
return;
}
response.text().then(function(data) {
console.log('Data in Console',data);
response_data = data;
console.log('Response Data',response_data);
response_jsonObj = JSON.parse(response_data);
console.log('Response JSON Object',response_jsonObj);
});
}).catch(error => this.setState({ error }));
}
render() {
return (
<div id = "id1">
<form onSubmit={this.handleSubmit}>
<label htmlFor="id">Enter id</label>
<input id="id" name="id" type="text" />
<label htmlFor="name">Enter Name</label>
<input id="name" name="name" type="text" />
<label htmlFor="Field1">Enter your Field1</label>
<input id="Field1" name="Field1" type="text" />
<label htmlFor="Field2">Enter your Field2</label>
<input id="Field2" name="Field2" type="text" />
<label htmlFor="Field3">Enter your Field3</label>
<input id="Field3" name="Field3" type="text" />
<label htmlFor="Field4">Enter your Field4</label>
<input id="Field4" name="Field4" type="text" />
<label htmlFor="Field5">Enter your Field5</label>
<input id="Field5" name="Field5" type="text" />
<label htmlFor="Field6">Enter your Field6</label>
<input id="Field6" name="Field6" type="text" />
<label htmlFor="Field7">Enter your Field7</label>
<input id="Field7" name="Field7" type="text" />
<label htmlFor="Field8">Enter your Field8</label>
<input id="Field8" name="Field8" type="text" />
<label htmlFor="Field9">Enter your Field9</label>
<input id="Field9" name="Field9" type="text" />
<label htmlFor="Field10">Enter your Field10</label>
<input id="Field10" name="Field10" type="text" />
<label htmlFor="Field11">Enter your Field11</label>
<input id="Field11" name="Field11" type="text" />
<button>Send data!</button>
</form>
</div>
);
}
}
export default App;
I'm not sure your fetch format is correct. Do this way.
fetch(POSTAPIURL, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
String1:"xyzabc",
String2:"ABCD"
})
}).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch( err => {
console.log(err);
});

How can i move value from angular form to server nodejs

- This is the html:
<body ng-controller="stripeController">
<form action="/stripe" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="from-row">
<lebel>
<span>Price:{{getTotal}}$</span>
<input type="hidden" data-stripe="number">
</lebel>
</div>
<div class="form-row">
<label>
<span>Card Number</span>
<input type="number" size="20" data-stripe="number">
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YY)</span>
<input type="text" size="2" data-stripe="exp_month">
</label>
<span> / </span>
<input type="text" size="2" data-stripe="exp_year">
</div>
<div class="form-row">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc">
</label>
</div>
<input type="submit" class="submit" value="Submit Payment">
</form>
</body>
This is the controller code:
app.controller('stripeController', function($scope, $http) {
$http.get('/api/me').success(function (response) {
$scope.userInfo = response;
$scope.isCartEmpty = true;
$scope.userCart = [];
if($scope.userInfo.cart.length>0){
$scope.isCartEmpty= false;
}
console.log($scope.isCartEmpty);
for(var i=0;i<$scope.userInfo.cart.length;i++){
$scope.userCart[i] = $scope.userInfo.cart[i].productId
}
var y = 0;
$scope.getTotal =0;
for(i=0;i<$scope.userCart.length;i++) {
$http.get('/api/product/' + $scope.userCart[i]).success(function
(response) {
$scope.userInfo.cart[y].name = response.name;
$scope.userInfo.cart[y].price = response.price;
$scope.getTotal+= response.price;
y++;
});
}
});
});
This is the node.js post function :
router.post('/stripe', function(req, res){
//Need to check if the cart empty than re-direct to catalog.
var stripe = require("stripe")(
"sk_test_mypass"
);
stripe.charges.create({
amount: ????? * 100,
currency: "usd",
source: req.body.stripeToken, // obtained with Stripe.js
description: "Test Charge"
}, function(err, charge) {
if(err){
console.log("Error");
}
console.log("Successfully bought product!");
});
});
-I have 1 questions:
In the node.js function where I put "?????" how can I get data from the
html form. When I type req.body.getTotal I don't get the data...
You'll want to send it in a hidden field, but it would be better to calculate the total from the product IDs and quantities in the Cart on the server side so there's no opportunity for the amount to be changed client side.