create multiple json object and pass in spring controller through ajax - html

<script>
$(document).ready(function() {
$("#frm_details").on("submit", function(event) {
event.preventDefault();
var data = $(this).serialize()
$.ajax({
url : "/saveUser",
type : "post",
contentType : "application/json",
data: JSON.stringify({ user: user, employee: employee, address: address }),
dataType : 'json',
success : function(d) {
location.replace("index.html");
}
});
});
});
This is HTML Registration form
<html lang="en"> <head> <title>Registration Form</title> </head>
<body> <div class="container"> <h1 class="well">Registration
Form</h1> <div class="col-lg-12 well"> <div class="row">
<form name="frm_details" id="frm_details" method="post">
<div class="row">
<div class="col-sm-6 form-group">
<label>First Name*</label> <input type="text" name="employeeName"
id="employeeName" placeholder="Enter First Name Here.."
class="form-control" required>
</div>
<div class="col-sm-6 form-group">
<label>Last Name*</label> <input type="text"
name="employeeSurName" id="employeeSurName"
placeholder="Enter Last Name Here.." class="form-control"
required>
</div>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label>Birth Date*</label>
<div class="input-append date">
<input type="text" class="form-control datepicker"
name="birthDay" id="birthDay"
placeholder="Enter Birth Date Here.." required>
</div>
</div>
<div class="col-sm-6 form-group">
<label>Mobile Number*</label> <input type="text"
placeholder="Enter Mobile Number Name .." class="form-control"
name="mobile" id="mobile" required>
</div>
</div>
<div class="row">
<div class="col-sm-4 form-group">
<label>Email Address*</label> <input type="email"
placeholder="Enter Email Address Here.." class="form-control"
name="userName" id="userName"
data-error="Please enter valid email address" required>
</div>
<div class="col-sm-4 form-group">
<label>Password*</label> <input type="password" id="password"
placeholder="Password" class="form-control" name="password"
data-minlength="6" required>
<div class="help-block">Minimum of 6 characters</div>
</div>
<div class="col-sm-4 form-group">
<label>Re-Password*</label> <input type="password"
data-match="#password" id="re_password" name="re_password"
data-match-error="Whoops,these don't match"
placeholder="Confirm" required class="form-control" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<div class="col-sm-4 form-group">
<label>House No*</label> <input type="text"
placeholder="Enter House Number Here.." class="form-control"
name="house_no" id="house_no">
</div>
<div class="col-sm-4 form-group">
<label>STREET NO</label> <input type="text"
placeholder="Street Number" class="form-control"
data-error="Street Number required" name="street_Name"
id="street_Name" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<div class="col-sm-4 form-group">
<label>State*</label> <select id="state" class="form-control"
data-error="State required" name="state" id="state" required>
<option value="" selected="selected">-- Select State--</option>
</select>
<div class="help-block with-errors"></div>
</div>
<div class="col-sm-4 form-group">
<label>City*</label> <select class="form-control" id="city"
name="city" data-error="City required" required>
<option value="" selected="selected">-- Select City--</option>
</select>
<div class="help-block with-errors"></div>
</div>
<div class="col-sm-4 form-group">
<label> Pin Code*</label> <input type="text" id="zip" name="zip"
placeholder="Enter Pin Code Number Here.."
data-error="Zip required" class="form-control" required>
</div>
<div class="help-block with-errors"></div>
</div>
<button type="submit" class="btn btn-lg btn-info">Submit</button>
<button type="reset" class="btn btn-lg btn-info">RESET</button>
</form> </div> </div> </div> <script type="text/javascript"> $('input.datepicker').each(function() {
var datepicker = $(this);
datepicker.bootstrapDatePicker(datepicker.data()); }); </script>
This controller class
#RequestMapping("/saveUser")
public String saveUser(#RequestBody String json) {
try {
if (!StringUtils.isEmpty(json))
return "1";
else
return "0";
} catch (Exception ex) {
return "1";
}
}
Iam getting this type result in json :
employeeName=Rajesh+XYZ&employeeSurName=xyz&birthDay=&mobile=213333123&userName=rajesh_xyz%40gmail.com&password=ssss&re_password=www&house_no=www&street_Name=Flat+No%3AA-27&state=Maharashtra&city=Latur&zip=411019
I have already three pojo object employee ,user,address.How could I pass this three object from ajax to cotroller

You should probably create some sort of request wrapper or command object for this.
public class RegistrationCommand {
private String employeeName;
private String password;
private String address;
//etc...
}
Then you can bind that request like this:
#RequestMapping("/saveUser")
public String saveUser(#RequestBody RegistrationCommand request) {
}
If you want to keep you existing json structure then I'd probably do something like:
public class RegistrationCommand {
private User user;
private Employee employee;
private Address address;
//etc...
private static class User {
private String name;
private String password;
//etc...
}
// Employee & Address classes
}

Related

how to get data from html form into a json format

I am building an ecommerce site. so, i created a billing form, and in that form, i want to collect stuffs like email, address etc and pass it into a json format so i'll pass it to the payment gateway.
I tried creating it in a variable and passing it, but on the payment gateway redirectedmodal form, it is saying invalid email input
Code
const publicKey = "{{ key }}";
var email = document.getElementById('email').value;
var fullname = document.getElementById('fullName').value;
var address1 = document.getElementById('custAdd').value;
var address2 = document.getElementById('custAdd2').value;
var country = document.getElementById('country').value;
var state = document.getElementById('state').value;
var address1 = document.getElementById('postCode').value;
function payWithRave() {
var x = getpaidSetup({
PBFPubKey: "xxxxxx",
email: email,
amount: '{{cart.get_total_price}}',
customer_phone: "234099940409",
currency: "USD",
address: 'address1',
address2: 'address2',
country: 'country',
state: 'state',
postcode: 'postCode',
})
<div class="col-sm-7">
<label for="firstName" class="form-label">Full Name</label>
<input type="text" class="form-control" id="fullName" placeholder="" required>
<div class="invalid-feedback">
Valid first name is required.
</div>
</div>
<div class="col-12">
<label for="email" class="form-label">Email <span class="text-muted">(Optional)</span></label>
<input type="email" class="form-control" id="email" placeholder="you#example.com">
<div class="invalid-feedback">
Please enter a valid email address for shipping updates.
</div>
</div>
<div class="col-12">
<label for="address" class="form-label">Address</label>
<input type="text" class="form-control" id="custAdd" placeholder="1234 Main St" required>
<div class="invalid-feedback">
Please enter your shipping address.
</div>
</div>
<div class="col-12">
<label for="address2" class="form-label">Address 2 <span
class="text-muted">(Optional)</span></label>
<input type="text" class="form-control" id="custAdd2" placeholder="Apartment or suite">
</div>
<div class="col-md-5">
<label for="country" class="form-label">Country</label>
<select class="form-select" id="country" required>
<option value="">Choose...</option>
<option>United States</option>
</select>
<div class="invalid-feedback">
Please select a valid country.
</div>
</div>
<div class="col-md-4">
<label for="state" class="form-label">State</label>
<select class="form-select" id="state" required>
<option value="">Choose...</option>
<option>California</option>
</select>
<div class="invalid-feedback">
Please provide a valid state.
</div>
</div>
<div class="col-md-3">
<label for="Postcode" class="form-label">Postcode</label>
<input type="text" class="form-control" id="postCode" placeholder="" required>
<div class="invalid-feedback">
Zip code required.
</div>
</div>
</div>
<hr class="my-4">
<button type="button" class="btn btn-primary w-100 fw-bold" onClick="payWithRave()">Pay ${{cart.get_total_price}}</button>
const publicKey = "{{ key }}";
const payWithRave = (ev) => {
ev.preventDefault();
let x = {
PBFPubKey: "xxxxxx",
fullname: document.getElementById('fullName').value,
email: document.getElementById('email').value,
amount: '{{cart.get_total_price}}',
customer_phone: "234099940409",
currency: "USD",
address: document.getElementById('custAdd').value,
address2: document.getElementById('custAdd2').value,
country: document.getElementById('country').value,
state: document.getElementById('state').value,
postcode: document.getElementById('postCode').value,
}
console.log(x);
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btn').addEventListener('click', payWithRave);
})
<!DOCTYPE html>
<html>
<body>
<div class="col-sm-7">
<label for="firstName" class="form-label">Full Name</label>
<input type="text" class="form-control" id="fullName" placeholder="" required>
<div class="invalid-feedback">
Valid first name is required.
</div>
</div>
<div class="col-12">
<label for="email" class="form-label">Email <span class="text-muted">(Optional)</span></label>
<input type="email" class="form-control" id="email" placeholder="you#example.com">
<div class="invalid-feedback">
Please enter a valid email address for shipping updates.
</div>
</div>
<div class="col-12">
<label for="address" class="form-label">Address</label>
<input type="text" class="form-control" id="custAdd" placeholder="1234 Main St" required>
<div class="invalid-feedback">
Please enter your shipping address.
</div>
</div>
<div class="col-12">
<label for="address2" class="form-label">Address 2 <span
class="text-muted">(Optional)</span></label>
<input type="text" class="form-control" id="custAdd2" placeholder="Apartment or suite">
</div>
<div class="col-md-5">
<label for="country" class="form-label">Country</label>
<select class="form-select" id="country" required>
<option value="">Choose...</option>
<option>United States</option>
</select>
<div class="invalid-feedback">
Please select a valid country.
</div>
</div>
<div class="col-md-4">
<label for="state" class="form-label">State</label>
<select class="form-select" id="state" required>
<option value="">Choose...</option>
<option>California</option>
</select>
<div class="invalid-feedback">
Please provide a valid state.
</div>
</div>
<div class="col-md-3">
<label for="Postcode" class="form-label">Postcode</label>
<input type="text" class="form-control" id="postCode" placeholder="required">
<div class="invalid-feedback">
Zip code required.
</div>
</div>
<hr class="my-4">
<button type="button" id="btn" class="btn btn-primary w-100 fw-bold">Pay ${{cart.get_total_price}}</button>
</body>
</html>
strong text

disable button until all inputs are filled in

I have this form:
<div class="modal-body">
<form action="repository/add_new_task.php">
<div class="form-group">
<label for="street" class="col-form-label">Street</label>
<input type="text" class="form-control" id="street">
</div>
<div class="form-group">
<label for="phone" class="col-form-label">Phone</label>
<input type="text" class="form-control" id="phone">
</div>
<div class="form-group">
<label for="date" class="col-form-label">Date</label>
<div class="input-group date" id="datetimepicker" data-target-input="nearest">
<input type="text" class="form-control datetimepicker-input" id="date" data-target="#datetimepicker">
<div class="input-group-append" data-target="#datetimepicker" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
<div class="form-group">
<label for="price" class="col-form-label">Price</label>
<input type="text" class="form-control" id="price">
</div>
<div class="form-group">
<label for="comment" class="col-form-label">Comment</label>
<textarea type="text" class="form-control" rows="3" id="comment"></textarea>
</div>
<div class="form-group">
<label for="job-type" class="col-form-label">Comment</label>
<select class="form-control" id="job-type">
<option value="0">Repair</option>
<option value="1">Multistory Pull In</option>
<option value="2">Multistory Weld</option>
<option value="3">Private Residence</option>
</select>
</div>
<button type="submit" class="btn btn-primary btn-block" name="new-task-submit">Create task</button>
</form>
</div>
All I need to do is to make button disabled until all the fields (including datepicker and textarea) have values in them.
I tried following the answer in this post and while it worked I struggles to make it work for my datepicker and textarea. Can someone please help me figure this out
With just css you can use pointer events and make the button unclickable.
form:invalid [type="submit"] {
pointer-events: none;
border: 1px solid #999999;
background-color: #CCCCCC;
color: #666666;
}
<form>
<input type="text" required />
<input type="text" required />
<input type="text" required />
<input type="submit" />
You can use oninput and .disabled like so:
var field1 = document.getElementById("date");
var field2 = document.getElementById("phone");
var field3 = document.getElementById("price");
var field4 = document.getElementById("comment");
var field5 = document.getElementById("job-type");
var button = document.getElementById("btn");
function validate(){
if(!isEmpty(field1)&&!isEmpty(field2)&&!isEmpty(field3)&&!isEmpty(field4)&&!isEmpty(field5)){
btn.disabled=false;
}else{
btn.disabled=true;
}
}
function isEmpty(element){
if(element.value.length==0){
return true;
}else{
return false;
}
}
<div class="modal-body">
<form action="repository/add_new_task.php">
<div class="form-group">
<label for="street" class="col-form-label">Street</label>
<input type="text" class="form-control" id="street" oninput="validate()">
</div>
<div class="form-group">
<label for="phone" class="col-form-label">Phone</label>
<input type="text" class="form-control" id="phone" oninput="validate()">
</div>
<div class="form-group">
<label for="date" class="col-form-label">Date</label>
<div class="input-group date" id="datetimepicker" data-target-input="nearest">
<input type="text" class="form-control datetimepicker-input" id="date" data-target="#datetimepicker" oninput="validate()">
<div class="input-group-append" data-target="#datetimepicker" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
<div class="form-group">
<label for="price" class="col-form-label">Price</label>
<input type="text" class="form-control" id="price" oninput="validate()">
</div>
<div class="form-group">
<label for="comment" class="col-form-label">Comment</label>
<textarea type="text" class="form-control" rows="3" id="comment" oninput="validate()"></textarea>
</div>
<div class="form-group">
<label for="job-type" class="col-form-label">Comment</label>
<select class="form-control" id="job-type" onchange="validate()">
<option value="0">Repair</option>
<option value="1">Multistory Pull In</option>
<option value="2">Multistory Weld</option>
<option value="3">Private Residence</option>
</select>
</div>
<button type="submit" id="btn" class="btn btn-primary btn-block" name="new-task-submit" disabled>Create task</button>
</form>
</div>
If the user has not entered any text into any of the fields, the button will be disabled automatically.

Binding json - formgroup

I have a form and I want to display data that comes from an API (JSon file) in mode readonly. Do you have tracks?
I take an example of a form:
Thank you
<div class="col-sm-8 col-sm-offset-2">
<form [formGroup]="userForm" (ngSubmit)="onSubmitForm()">
<div class="form-group">
<label for="firstName">Prénom</label>
<input type="text" id="firstName" class="form-control" formControlName="firstName">
</div>
<div class="form-group">
<label for="lastName">Nom</label>
<input type="text" id="lastName" class="form-control" formControlName="lastName">
</div>
<div class="form-group">
<label for="email">Adresse e-mail</label>
<input type="text" id="email" class="form-control" formControlName="email">
</div>
<div class="form-group">
<label for="email">Adresse address</label>
<input type="text" id="address" class="form-control" formControlName="address">
</div>
<button type="submit" class="btn btn-primary">Soumettre</button>
</form>
</div>
File JSON
User:
- User1:
firstName: toto
lastName: titi
email: toto#toto.com
address: 2 rue titi
In your component (.ts file), as soon as the data comes back (typically inside of your ngOnInit), you should be able to do this.userForm.setValue(data).
As for making them readonly, an easy way I know is to set the FormGroup as disabled when you create it. So userForm = new FormGroup({_property_names_}, { disabled: true }).

How to get json and display it by user id

I want to display the data of the selected user in angular 2. I make a service to get the data from API
getUserById(id: string): Promise<User> {
const url ='api/user/${id}';
return this.httpClient.get(url)
.toPromise()
.then(response => response.json() as User)
.catch(this.handleError); }
and this is my controller
user: User;
constructor(private userService: UserService) {
userService.getUserById('45835708-f55a-40fb-878f-33b9c920e196')
.then(hasil => this.user = hasil)
.catch(this.handleError);
}
and here is my template
<div class="form-group">
<label class="col-sm-2 control-label">FULL NAME</label>
<div class="col-sm-6">
<input class="form-control" type="text" value="" disabled>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">USER NAME</label>
<div class="col-sm-6">
<input class="form-control" type="text" value="" disabled>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">PASSWORD</label>
<div class="col-sm-6">
<input class="form-control" type="password" value="" disabled>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">DATE OF BIRTH</label>
<div class="col-sm-6">
<input class="form-control" type="text" value="" disabled>
</div>
</div>
How to display the json to my template? Do I make correct service and controller?
You can choose to use template driven forms or reactive driven forms.
this.user object can be a model to that form, and when you input something into html input elements, object will update automatically:
<div class="form-group">
<label class="col-sm-2 control-label">FULL NAME</label>
<div class="col-sm-6">
<input class="form-control" type="text" value="" [(ngModel)]="user.fullName" disabled>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">USER NAME</label>
<div class="col-sm-6">
<input class="form-control" type="text" value="" [(ngModel)]="user.username" disabled>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">PASSWORD</label>
<div class="col-sm-6">
<input class="form-control" type="password" value="" [(ngModel)]="user.password" disabled>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">DATE OF BIRTH</label>
<div class="col-sm-6">
<input class="form-control" type="date" value="" [(ngModel)]="user.dateOfBirth" disabled>
</div>
</div>
If you want to add some validator, you should go with Reactive forms:
https://angular.io/docs/ts/latest/guide/reactive-forms.html
The principle here is to create a form group and define individual properties with their initial values and validator.
First make sure you have FormsModule imported in your module. Then... remember to use ngModel to bind the user to the form.
But, forms do not care about ngModel unless there is also a name attribute on each field:
<input class="form-control" name="fullName" [ngModel]="user.fullName">
OR
ngModelOptions in each field:
<input class="form-control" [ngModelOptions]="{standalone: true}" [ngModel]="user.fullName">
Here's a demo for you with usage of the name attribute:
Plunker

How to call the HttpPost ActionResult in MVC5?

I have a contact view in my app, and it contains a form, which is defined as below:
<form role="form" style="width:100%; float:left;">
<div class="form-group">
<img src="~/Content/img/zarf.png" class="zarf-pos">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Name and Surname</label>
<input type="text" name="fullName" class="form-control" id="exampleInputEmail1" placeholder="Enter your full name" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">E-Mail</label>
<input type="email" name="emailAddress" class="form-control" id="exampleInputPassword1" placeholder="Enter your e-mail address" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Write to us</label><br>
<textarea name="message" class="form-control" rows="5" placeholder="How can we help you?" required></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default reg-position">Send</button>
</div>
</form>
Then, in my controller, I have two ActionResults, one HttpGet, and one HttpPost, defined like this:
[HttpGet]
public ActionResult Contact()
{
return View();
}
[HttpPost]
public ActionResult Contact(string fullName, string emailAddress, string message)
{ // some functionality }
But, when I fill out the form and click the Send button, it redirect to the empty Contact page. The point is that I need to have two Contact methods, while in my Post method I have some code that assumes that the strings are not empty. And if I have just one contact method, I get an error message saying the string is null, and the view is not displayed. So, I decided to have two methods, but don't know how to call the post method when the button is pressed.
Assuming you are using Razor to create your views, define the form like so:
#using( Html.BeginForm() )
{
<div class="form-group">
<img src="~/Content/img/zarf.png" class="zarf-pos">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Name and Surname</label>
<input type="text" name="fullName" class="form-control" id="exampleInputEmail1" placeholder="Enter your full name" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">E-Mail</label>
<input type="email" name="emailAddress" class="form-control" id="exampleInputPassword1" placeholder="Enter your e-mail address" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Write to us</label><br>
<textarea name="message" class="form-control" rows="5" placeholder="How can we help you?" required></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default reg-position">Send</button>
</div>
}
This will ensure the correct <form> element is generated to post back to your action.
P.S. Just some nomenclature housekeeping... You don't call an ActionResult, you call Actions and they return ActionResults. It'll help when you're talking to other developers if you're using the correct names for things.