I am using version 2.28, I am having some issues trying to click a
button that redirects me twice to different URLs.
The result of the click method it is an UnexpectedPage ... (response
status code 200).
I tried to set:
webClient.getCache().setMaxSize(0);
webClient.getOptions().setRedirectEnabled(true);
but I can't reach the page after. I have JavaScript enable.
this is a web written in PHP
the button is currently doing this:
$.ajax({
url: '{{ action('LoanController#checkLoanProcessed') }}',
data: data,
type: 'POST',
cache: false,
dataType: "json",
success: function(data) {
if (data.status === true && data.processed === true)
{
clearInterval(interval); window.location.href = data.redirect; }
}
});
};
Any clue ?
HTML
<script>var SITE_URL = 'https://staging.tutasa.com.uy/';</script>
<script type="text/javascript">
var user_id = '49095';
var user_first_name = 'JUAN';
var duration_6 = "6 Months";
var duration_1 = '1 Year';
var duration_2 = '2 Years';
var duration_3 = '3 Years';
var duration_4 = '4 Years';
var duration_6_quota = '6 Quotas';
var duration_1_quota = '12 Quotas';
var duration_2_quota = '24 Quotas';
var duration_3_quota = '36 Quotas';
var duration_4_quota = '48 Quotas';
var quota_label = [];
quota_label['quota_0'] = '6 Monthly Quotas of:';
quota_label['quota_1'] = '12 Monthly Quotas of:';
quota_label['quota_2'] = '24 Monthly Quotas of:';
quota_label['quota_3'] ='36 Monthly Quotas of:';
quota_label['quota_4'] = '48 Monthly Quotas of:';
var borrower_page = true;
var lender_page = false;
</script>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>
TuTasa - Your Account </title>
<link rel="stylesheet" type="text/css" href="https://staging.tutasa.com.uy/layouts/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="https://staging.tutasa.com.uy/layouts/css/datepicker3.css">
<link rel="stylesheet" type="text/css" href="https://staging.tutasa.com.uy/css/app.css?1512484810">
<link rel="stylesheet" type="text/css" href="https://staging.tutasa.com.uy/css/app2.css?1512484810">
<link rel="stylesheet" type="text/css" href="https://staging.tutasa.com.uy/layouts/css/bootstrap-slider.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://staging.tutasa.com.uy/layouts/js/jquery.min.js"></script>
<script type="text/javascript">
var CURRENCY_SYMBOL = '$U';
var CURRENCY_THOUSAND_SEP = ',';
var CURRENCY_DEC_POINT = '.';
var THOUSAND_SEP = ',';
var DEC_POINT = '.';
</script>
</head>
<body>
<div id="wrap" class="container-fluid">
<div id="main" class="row clearfix">
<div class="col-sm-offset-2 col-sm-8 col-md-offset-1 col-md-10 main">
<div class="container-fluid create-new-loan ">
<div class="panel panel-default">
<div class="panel-body pl0 pr0">
<div class="row bs-wizard" style="border-bottom:0;">
<div class="col-xs-3 bs-wizard-step complete">
<div class="progress"><div class="progress-bar"></div></div>
1
<div class="text-center bs-wizard-stepnum">1. Personal</div>
</div>
<div class="col-xs-3 bs-wizard-step active"><!-- complete -->
<div class="progress"><div class="progress-bar"></div></div>
2
<div class="text-center bs-wizard-stepnum">2. Income</div>
</div>
<div class="col-xs-3 bs-wizard-step disabled"><!-- complete -->
<div class="progress"><div class="progress-bar"></div></div>
3
<div class="text-center bs-wizard-stepnum">3. Decision</div>
</div>
<div class="col-xs-3 bs-wizard-step disabled"><!-- active -->
<div class="progress"><div class="progress-bar"></div></div>
4
<div class="text-center bs-wizard-stepnum">4. Money</div>
</div>
</div>
<form method="POST" action="https://staging.tutasa.com.uy/loan/create" accept-charset="UTF-8" class="form-horizontal"><input name="_token" type="hidden" value="BXLImooTL1DnEn4ouSi4uCJ1GG4fZawTdRkRzDtG">
<input name="int" type="hidden" value="">
<input name="user_id" type="hidden" value="49095">
<input name="type" type="hidden" value="borrower">
<div class="panel panel-default hidden">
<div class="panel-heading">Income</div>
<div class="panel-body">
<input type="hidden" name="borrow_amount_min" value="10000.00"/>
<input type="hidden" name="borrow_amount_max" value="200000.00"/>
<div class="form-group">
<label for="education" class="col-sm-4 control-label">Education<span class="required"> *</span></label>
<div class="col-sm-4">
<select class="form-control" id="education" name="education"><option value=""></option><option value="1">Primary</option><option value="2">Secondary</option><option value="3">University</option><option value="4" selected="selected">Post Graduate</option><option value="5">Other</option></select>
</div>
</div>
<div class="form-group">
<label for="income_type" class="col-sm-4 control-label">Means of Income<span class="required"> *</span></label>
<div class="col-sm-4">
<select class="form-control" id="income_type" name="income_type"><option value=""></option><option value="1">Employee</option><option value="2">Businessman</option><option value="3">Independent Professional</option><option value="4">Pension</option><option value="5">Allowances</option><option value="6" selected="selected">Rent</option><option value="7">Unemployed</option></select>
</div>
</div>
<div class="hidden income-employee income-1">
<div class="form-group">
<label for="company_name" class="col-sm-4 control-label">Company Name<span class="required"> *</span></label>
<div class="col-sm-4">
<input class="form-control" name="company_name" type="text" value="" id="company_name">
</div>
</div>
<div class="form-group">
<label for="job_title" class="col-sm-4 control-label">Job Title</label>
<div class="col-sm-4">
<input class="form-control" name="job_title" type="text" value="" id="job_title">
</div>
</div>
<div class="form-group">
<label for="company_phone_no" class="col-sm-4 control-label">Company telephone number<span class="required"> *</span></label>
<div class="col-sm-4">
<input class="form-control" name="company_phone_no" type="text" value="" id="company_phone_no">
</div>
</div>
<div class="form-group">
<label for="company_supervisor" class="col-sm-4 control-label">Name of Supervisor<span class="required"> *</span></label>
<div class="col-sm-4">
<input class="form-control" name="company_supervisor" type="text" value="" id="company_supervisor">
</div>
</div>
<div class="form-group">
<label for="job_duration" class="col-sm-4 control-label">How long have you been with this job?<span class="required"> *</span></label>
<div class="col-sm-4">
<select class="form-control" id="job_duration" name="job_duration"><option value="6" selected="selected">Less then 6 months</option><option value="12">6 months to 1 year</option><option value="24">1 year to 2 years</option><option value="36">2 years to 3 years</option><option value="37">More than 3 years</option></select>
</div>
</div>
</div>
<div class="form-group">
<label for="monthly_income" class="col-sm-4 control-label">What's your monthly net income?<span class="required"> *</span></label>
<div class="col-sm-4">
<input class="form-control" name="monthly_income" type="text" value="350000" id="monthly_income">
</div>
<div class="col-sm-4">
<label class="disclosure">Need to show proof of income</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<input class="form-control" id="monthly_income_text" readonly="true" name="monthly_income_text" type="text" value="Trescientos cincuenta mil">
</div>
</div>
<div class="form-group">
<label for="proof_of_income" class="col-sm-4 control-label">Do you have proof of income?<span class="required"> *</span></label>
<div class="col-sm-4">
<select class="form-control" id="proof_of_income" name="proof_of_income"><option value="Select">Select</option><option value="Yes" selected="selected">Yes</option><option value="No">No</option><option value="Maybe">Maybe</option></select>
</div>
</div>
<div class="form-group">
<label for="bank_account" class="col-sm-4 control-label">Do you have bank account under your name?<span class="required"> *</span></label>
<div class="col-sm-4">
<select class="form-control" id="bank_account" name="bank_account"><option value="Select">Select</option><option value="Yes" selected="selected">Yes</option><option value="No">No</option><option value="Yes, but I don't remember the details">Yes, but don't remember details</option></select>
</div>
</div>
<input type="hidden" name="calculate_status" class="form-control" value="1" />
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<input class="btn btn-primary btn-lg" name="calculate" type="submit" value="How much can I borrow?">
</div>
</div>
</div>
</div>
<input name="temp_amount" type="hidden" value="30000.0000">
<input name="temp_duration" type="hidden" value="0">
<div class="panel panel-default loan_amt_duration">
<div class="panel-heading">
Find below the maximum you can borrow based on the information provided.
</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
<div class="col-sm-12">
<h3>
Amount
</h3>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="col-sm-10 mt-15">
<a class="amountSliderDecrease" href="#">
<span class="glyphicon glyphicon-minus mr-15"></span>
</a>
<input id="amount" name="amount" data-slider-id='amountSlider' data-slider-class="slider-long" type="text" data-slider-min="10000.00" data-slider-max="200000.00" data-slider-step="10000" data-slider-value="30000.0000"/>
<a class="amountSliderIncrease" href="#">
<span class="glyphicon glyphicon-plus ml-15"></span>
</a>
</div>
<div class="col-sm-2 mt-15">
<input id="amount-manual-loan" name="amount-manual" class="amount-manual text-center" min="10000.00" max="200000.00"/>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="col-sm-12">
<h3>
Loan Duration
</h3>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="col-sm-10 mt-15">
<a class="durationSliderDecrease" href="#">
<span class="glyphicon glyphicon-minus mr-15"></span>
</a>
<input id="duration" name="duration" data-slider-id='durationSlider' type="text" data-slider-min="0" data-slider-max="4" data-slider-step="1" data-slider-value="0"/>
<a class="durationSliderIncrease" href="#">
<span class="glyphicon glyphicon-plus ml-15"></span>
</a>
</div>
</div>
</div>
<div class="pt-40 col-sm-12">
<div class="row totals">
<div id="borrower-data-url" data-url="https://staging.tutasa.com.uy/borrower/repayment-calculate" class="hide"></div>
<div class="col-md-3 mb-25 selected-result">
<span id="borrow_amount">$U 30,000</span>
<span class="amt_label">Total Amount</span>
</div>
<div class="col-md-3 mb-25 selected-result">
<span class="borrow_quota_display">$U 6,171</span>
<span id="borrow_quota_label" class="amt_label">
6 Monthly Quotas of:<sup>*</sup>
</span>
</div>
<div class="col-md-3 mb-25 selected-result">
<span class="borrow_rate_display">30.84%</span>
<span class="amt_label">Interest Rate</span>
</div>
<div class="col-md-3 mb-25">
<button id="credit_score" onClick="void(0)" style="cursor:pointer;" class="btn btn-block btn-success btn-lg col-sm-12" name="review" type="submit" value="Proceed to credit scoring">Proceed to credit scoring</button>
<button id="credit_score" onClick="void(0)" style="cursor:pointer; margin-top:15px;" class="btn btn-block btn-primary btn-lg col-sm-12" name="back_to_income" type="submit" value="Back">Back</button>
</div>
<input name="borrow_quota" type="hidden" value="6171">
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<p>*Representative APR <span id="borrow_rate" class="borrow_rate borrow_rate_display">30.84</span>%. Terms subject to market conditions.</p>
</div>
<script type="text/javascript">
$(document).ready(function(){
if(false){
$('input[name="calculate"]').click();
}
$('#monthly_income').inputmask('[999999999]', {"numericInput": true, "greedy": false, "placeholder": ""});
$('#monthly_income').on('keyup', _.debounce(function(){
monthlyIncomeText();
}, 1000));
_.each(['input[name="borrow_quota"]','#purpose','#education','#priority','#income_type','#company_name','#job_title','#company_phone_no','#company_supervisor','#job_duration','#businessman_org_name',
'#businessman_org_phone','#businessman_ref','#indep_prof_industry','#indep_prof_ref','#indep_prof_ref_phone','#retired_prev_employer_name','#allow_grantor','#unemp_prev_employer_name',
'#monthly_income','#proof_of_income','#bank_account','#repayment_likelihood','#calculate_status','#fast_track_code','#fast_track_code_status','#amount_payable_to'], function(input){
$(input).change(function(){
var data = {};
if($('#amount').val()) data[btoa('amount')] = btoa($('#amount').val());
if($('#duration').val()) data[btoa('duration')] = btoa($('#duration').val());
if($('#borrow_rate').text()) data[btoa('rate')] = btoa($('#borrow_rate').text());
if($('input[name="borrow_quota"]').val()) data[btoa('quota')] = btoa($('input[name="borrow_quota"]').val());
if($('input[name="borrow_quota"]').val()) data[btoa('total')] = btoa($('#duration').val() ? 0.5 * 12 * $('input[name="borrow_quota"]').val() : $('#duration').val() * $('input[name="borrow_quota"]').val());
if($('#education').val()) data[btoa('education')] = btoa($('#education').val());
if($('#priority').val()) data[btoa('priority')] = btoa($('#priority').val());
if($('#income_type').val()) data[btoa('income_type')] = btoa($('#income_type').val());
if($('#monthly_income').val()) data[btoa('monthly_income')] = btoa($('#monthly_income').val());
if($('#proof_of_income').val()) data[btoa('proof_of_income')] = btoa($('#proof_of_income').val());
if($('#proof_of_income').val()) data[btoa('proof_of_income')] = btoa($('#proof_of_income').val());
if($('#bank_account').val()) data[btoa('bank_account')] = btoa($('#bank_account').val());
if(input.indexOf('#') != -1){
data[btoa(input.replace('#', ''))] = btoa($(input).val());
}
data[btoa('user_id')] = btoa(49095);
data[btoa('type')] = btoa('borrower');
data['_token'] = $('form').find('input[name="_token"]').val();
$.ajax({
url: 'https://staging.tutasa.com.uy/loan/save-temp-loan',
data: data,
type: 'POST',
cache: false,
dataType: "json"
});
});
});
$('#fast_track_code_status').val('');
$('.fast_track_code_error').hide();
if($('#fast_track_code').val() != '') {
if($('#fast_track_code_apply').length > 0) {
$( "#fast_track_code_apply" ).trigger( "click" );
}
}
function showIncomeFields(){
$('.income-employee').addClass('hidden');
$('.income-businessman').addClass('hidden');
$('.income-independent-professional').addClass('hidden');
$('.income-retired').addClass('hidden');
$('.income-allowances').addClass('hidden');
$('.income-rent').addClass('hidden');
$('.income-unemployed').addClass('hidden');
$('.income-'+$('#income_type').val()).removeClass('hidden');
}
showIncomeFields();
$('#income_type').change(function(){
showIncomeFields();
});
function monthlyIncomeText(){
console.log($('#monthly_income').val());
if($('#monthly_income').length && $.isNumeric($('#monthly_income').val()) && $('#monthly_income').val() > 0){
var data = {};
data[btoa('number')] = btoa($('#monthly_income').val());
data['_token'] = $('form').find('input[name="_token"]').val();
$.ajax({
url: 'https://staging.tutasa.com.uy/borrower/numbers-to-words',
data: data,
type: 'POST',
cache: false,
dataType: "json",
success: function(data) {
console.log(data);
if (data.status === true) {
$('#monthly_income_text').val(data.text.substr(0,1).toUpperCase() + data.text.substr(1));
}else{
$('#monthly_income_text').val('');
}
},
error: function(error) {
console.log(error);
$('#monthly_income_text').val('');
}
});
}else{
$('#monthly_income_text').val('');
}
}
monthlyIncomeText();
});
</script>
</div>
</div>
</div>
<script src="https://staging.tutasa.com.uy/js/underscore-min.js"></script>
<script src="https://staging.tutasa.com.uy/js/pdf/build/pdf.js"></script>
<script src="https://staging.tutasa.com.uy/layouts/js/bootstrap.js"></script>
<script src="https://staging.tutasa.com.uy/layouts/js/bootstrap-datepicker.js"></script>
<script src="https://staging.tutasa.com.uy/layouts/js/angular.min.js"></script>
<script src="https://staging.tutasa.com.uy/js/bootbox.min.js"></script>
<script src="https://staging.tutasa.com.uy/layouts/js/bootstrap-slider.js"></script>
<script src="https://staging.tutasa.com.uy/layouts/js/heartcode-canvasloader-min.js"></script>
<script src="https://staging.tutasa.com.uy/js/inputmask/inputmask.js"></script>
<script src="https://staging.tutasa.com.uy/js/inputmask/jquery.inputmask.js"></script>
<script src="https://staging.tutasa.com.uy/js/inputmask/inputmask.numeric.extensions.js"></script>
<script src="https://staging.tutasa.com.uy/js/sliders.js?1512484810"></script>
<script src="https://staging.tutasa.com.uy/js/scripts.js?1512484810"></script>
</body>
</html>
Related
I'm trying to upload multiple files to springboot server from angular but I don't know why I'm getting error.But in postman the code is working fine and I'm able to upload files and output format.
I'm getting this error in browser
HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "OK", url: 'http://localhost:8080/file/Upload', ok: false, …}
Error in backend terminal:
DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'fileN' is not present]
springboot restapi:
#postMapping(value="/Upload")
public ResponseEntity<List<String>> uploadFiles(#RequestParam ("fileN")List<MultipartFile> multipartFiles,#RequestParam("fileFormat")String id) throws IOException, FOPException, TransformerException{
List<String> filenames = new ArrayList<>();
try{
for(MultipartFile file : multipartFiles){
String filename = StringUtils.cleanPath(file.getOriginalFilename());
Path fileStorage = get(DIRECTORY, filename).toAbsolutePath().normalize();
copy(file.getInputStream(), fileStorage, REPLACE_EXISTING);
filenames.add(filename);
}
fileConversion.Convert(id);
}
catch (Exception e){
e.printStackTrace();
}
return ResponseEntity.ok().body(filenames);
user service:
constructor(private http: HttpClient){}
uploadFile(formData: FormData): Observable<any>{
const headerDist = {
'Access-Control-Allow-Origin': '*';
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
'access-control-allow-credentials':'true'
'Content-Type': 'multipart/form data; boundary=Inflow'
}
const requestOptions = {
headers: new HttpHeaders(headerDist),
};
return this.http.post('http://localhost:8080/file/Upload',formData,requestOptions);
}
appcomponent:
onSubmit(){
const formData = new formData();
formData.append('fileN', this.angForm.get('file1').value);
formData.append('fileN', this.angForm.get('file2').value);
formData.append('fileN', this.angForm.get('file3').value);
formData.append('fileN', this.angForm.get('fileFormat').value);
this.userService.uploadFile(formData).subscribe (
(res) => console.log(res),
(err) => console.log(err)
)};
html:
<h2 id="zone" xmlns="http://www.w3.org/1999/html">File Conversions</h2>
<form [formGroup]="angForm" enctype="multipart/form-data" (ngSubmit)="onSubmit()" >
<div class="main">
<div class="classOne">
<div class="form-two">
<input type="file" class="file-input" formControlName="file1" id="ixml" value="" accept="xml/*" required (change)='uploadF($any($event.target).files)' #open>
<div class="file-upload">
<p class="para-tag">Input XML :</p>
<button mat-raised-button color="primary" class="upload-btn" (click)="open.click()">Choose File</button>
</div>
</div>
</div>
<div *ngIf="angForm.controls['file1'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['file1'].errors.required"></div>
</div>
<div class="classTwo">
<div class="form-two">
<input type="file" class="file-input" formControlName="file2" id="udtd" value="" accept="dtd/*" required (change)="uploadFile($event.target.files)"#ele>
<div class="file-upload">
<p class="para-tag">Upload DTD : </p>
<button mat-raised-button color="primary" class="upload-btn" (click)="ele.click()">Choose File</button>
</div>
</div>
</div>
<div *ngIf="angForm.controls['file2'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['file2'].errors.required"></div>
</div>
<div class="classThree">
<div class="form-two">
<input type="file" class="file-input" formControlName="file3" id="uxsl" value="" accept="xsl/*" required (change)="uploading($event.target.files);"#choose>
<div class="file-upload">
<p class="para-tag">Upload XSL : </p>
<button mat-raised-button color="primary" class="upload-btn" (click)="choose.click()">Choose File</button>
</div>
</div>
</div>
<div *ngIf="angForm.controls['file3'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['file3'].errors.required"></div>
</div>
<div class="classFour">
<p class="para-tag-two">Choose Your Output Format :</p>
<div>
<input type="radio" id="pdf" value="pdf" name="fileFormat" formControlName="fileFormat">
<label for="pdf">PDF</label><br>
<input type="radio" id="ps" value="ps" name="fileFormat" formControlName="fileFormat">
<label for="ps">PostScript</label><br>
<input type="radio" id="png" value="png" name="fileFormat" formControlName="fileFormat">
<label for="png">PNG</label><br>
<input type="radio" id="txt" value="txt" name="fileFormat" formControlName="fileFormat">
<label for="txt">Text</label><br>
<input type="radio" id="print" value="print" name="fileFormat" formControlName="fileFormat">
<label for="print">Print</label><br><br>
</div>
</div>
<div *ngIf="angForm.controls['fileFormat'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['fileFormat'].errors.required"></div>
</div>
<div class="submit">
<button style="width:100px;" type="submit" [disabled]="angForm.invalid" mat-raised-button color="warn"disabled="true" >Submit</button>
</div>
</div>
</form>
Here I have a form that accepts package details and I have added dynamic form fields to get all the itineraries of that package. Please comment on what I must add to my question to make it more clear.
insert function
#PostMapping("/save-tour-package")
public String saveTourPackage(#ModelAttribute("tourPackage") TourPackage tourPackage, #RequestParam String[] day, #RequestParam String[] itinerary_title, #RequestParam String[] itinerary_description, #RequestParam String[] itinerary_altitude) {
// save package to database
TourPackage tour = tourPackageService.saveTourPackage(tourPackage);
for (int i = 0; i < day.length; i++) {
Itinerary ite = new Itinerary();
ite.setPackages(tour);
ite.setDay(day[i]);
ite.setTitle(itinerary_title[i]);
ite.setDescription(itinerary_description[i]);
ite.setAltitude(itinerary_altitude[i]);
itineraryRepo.save(ite);
}
return "redirect:/";
}
save service implementation
#Override
public TourPackage saveTourPackage(TourPackage tourPackage) {
return this.tourPackagesRepo.save(tourPackage);
}
view file
<div layout:fragment="content">
<div class="container">
<form th:action="#{/save-tour-package}" th:object="${tourPackage}" method="POST">
<div class="form-group">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" th:field="*{title}" placeholder="Title">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" id="description" th:field="*{description}"
placeholder="Description"></textarea>
</div>
<div class="row">
<div class="col-3">
<div class="form-group">
<label for="geography">Geography</label>
<input type="text" class="form-control" id="geography" th:field="*{geography}"
placeholder="Geography">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control" id="location" th:field="*{location}"
placeholder="Location">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="difficulty">Difficulty</label>
<input type="text" class="form-control" id="difficulty" th:field="*{difficulty}"
placeholder="Difficulty">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="altitude">Altitude</label>
<input type="text" class="form-control" id="altitude" th:field="*{altitude}"
placeholder="Altitude">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="religion">Religion</label>
<input type="text" class="form-control" id="religion" th:field="*{religion}"
placeholder="Title">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="ethnic_people">Ethnic People</label>
<input type="text" class="form-control" id="ethnic_people" th:field="*{ethnic_people}"
placeholder="Ethnic People">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="accommodation">Accommodation</label>
<input type="text" class="form-control" id="accommodation" th:field="*{accommodation}"
placeholder="Title">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="transportation">Transportation</label>
<input type="text" class="form-control" id="transportation" th:field="*{transportation}"
placeholder="Transportation">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="minimum_pax">Minimum Pax</label>
<input type="text" class="form-control" id="minimum_pax" th:field="*{minimum_pax}"
placeholder="Minimum Pax">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="price">Price</label>
<input type="text" class="form-control" id="price" th:field="*{price}" placeholder="Price">
</div>
</div>
</div>
<div class="row">
<div class="col-2">Day</div>
<div class="col-3">Title</div>
<div class="col-3">Description</div>
<div class="col-3">Altitude</div>
<div class="col-1"></div>
</div>
<div class="row delete-field append-new-field">
<div class="col-2">
<input type="text" class="form-control" name="day">
</div>
<div class="col-3">
<input type="text" class="form-control" name="itinerary_title">
</div>
<div class="col-3">
<input type="text" class="form-control" name="itinerary_description">
</div>
<div class="col-3">
<input type="text" class="form-control" name="itinerary_altitude">
</div>
<div class="col-1">
<i class="fas fa-minus-circle"></i>
</div>
</div>
Add Fields
<div class="form-group">
<button type="submit" class="btn btn-info col-2"> Save Tour Package</button>
</div>
</div>
</form>
</div>
</div>
<div layout:fragment="after-script">
<script>
function addItineraryFields() {
var html = '<div class="row delete-field"><div class="col-2">\n' +
' <input type="text" class="form-control" name="day">\n' +
' </div>\n' +
' <div class="col-3">\n' +
' <input type="text" class="form-control" name="itinerary_title">\n' +
' </div>\n' +
' <div class="col-3">\n' +
' <input type="text" class="form-control" name="itinerary_description">\n' +
' </div>\n' +
' <div class="col-3">\n' +
' <input type="text" class="form-control" name="itinerary_altitude">\n' +
' </div>' +
' <div class="col-1">\n' +
' <i class="fas fa-minus-circle"></i>\n' +
' </div></div>';
$('.append-new-field').append(html);
}
$(document).on('click', '.delete-row', function(e) {
$(this).closest('.delete-field').remove();
return false;
});
</script>
</div>
This is my Controller:
package br.com.apptrechos.torcidapremiada.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties.User;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import br.com.apptrechos.torcidapremiada.model.Beneficio;
import br.com.apptrechos.torcidapremiada.model.Imovel;
import br.com.apptrechos.torcidapremiada.model.Partida;
import br.com.apptrechos.torcidapremiada.repository.Imoveis;
import br.com.apptrechos.torcidapremiada.repository.Partidas;
import br.com.apptrechos.torcidapremiada.service.BeneficioService;
import br.com.apptrechos.torcidapremiada.service.exception.DadoJaCadastradoException;
#Controller
#RequestMapping("/beneficio")
public class BeneficioController {
#Autowired
private Partidas partidas;
#Autowired
private Imoveis imoveis;
#Autowired
private BeneficioService beneficioService;
#PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody ResponseEntity<?> validarBeneficio(#RequestBody Long codigo, #AuthenticationPrincipal User user) {
try {
Imovel imovel = this.imoveis.findByCodigoIn(codigo);
Partida proximaPartida = this.partidas.buscarProximaPartida();
Beneficio beneficio = new Beneficio(proximaPartida, user.getName(), imovel, imovel.getContribuinte());
this.beneficioService.salvar(beneficio);
} catch (DadoJaCadastradoException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
return ResponseEntity.ok().build();
}
}
My Javascript and my view:
var TorcidaPremiada = TorcidaPremiada || {};
TorcidaPremiada.ImovelConcederBeneficio = (function() {
function ImovelConcederBeneficio() {
this.validaBeneficioBtn = $('.js-valida-beneficio-btn');
this.containerMensagemErro = $('.js-container-mensagem-erro');
this.containerMensagemSucesso = $('.js-container-mensagem-sucesso');
}
ImovelConcederBeneficio.prototype.iniciar = function() {
this.validaBeneficioBtn.on('click', onBotaoValidaBeneficioClick.bind(this));
}
function onBotaoValidaBeneficioClick(event) {
var botao = $(event.currentTarget);
var codigo = botao.data('codigo');
var url = botao.data('url');
$.ajax({
url: url,
method: 'POST',
data: JSON.stringify({codigo: codigo}),
contentType: 'application/json',
success: onSuccess.bind(this),
error: onError.bind(this)
});
}
function onSuccess() {
var mensagem = 'Benefício concedido com sucesso!';
this.containerMensagemSucesso.removeClass('hidden');
this.containerMensagemSucesso.html('<span>' + mensagem + '</span>');
}
function onError(object) {
console.log(error);
var mensagem = object.responseText;
this.containerMensagemErro.removeClass('hidden');
this.containerMensagemErro.html('<i class="fa fa-exclamation-circle"></i><span> ' + mensagem + '</span>');
}
return ImovelConcederBeneficio;
}());
$(function() {
var imovelConcederBeneficio = new TorcidaPremiada.ImovelConcederBeneficio();
imovelConcederBeneficio.iniciar();
});
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
xmlns:tp="http://www.apptrechos.com.br"
xmlns:data="http://www.thymeleaf.org/extras/data"
layout:decorate="~{layout/layout-padrao}">
<head>
<title>Torcida Premiada - Cadastro de Imóveis</title>
<link rel="stylesheet" type="text/css" th:href="#{/stylesheets/vendors/bootstrap-switch.min.css}" />
</head>
<section layout:fragment="conteudo">
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2 th:if="${imovel.novo}">Cadastro de Imóveis</h2>
<h2 th:unless="${imovel.novo}">Edição de Imóvel</h2>
<ul class="nav navbar-right panel_toolbox">
<li>
<a th:href="#{/imovel}"><i class="fa fa-search"></i> <span>Pesquisa de Imóveis</span></a>
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br />
<form method="POST" class="form-horizontal form-label-left" th:object="${imovel}" th:action="#{/imovel/novo}">
<tp:message />
<div class="alert alert-danger alert-dismissible fade in hidden js-container-mensagem-erro" role="alert"></div>
<div class="alert alert-success alert-dismissible fade in hidden js-container-mensagem-sucesso" role="alert"></div>
<input type="hidden" th:field="*{codigo}" />
<div class="form-group tp-required" tp:classforerror="inscricaoImobiliaria">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="inscricaoImobiliaria">Inscrição Imobiliária</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" id="inscricaoImobiliaria" maxlength="16" class="form-control col-md-7 col-xs-12 input-imobiliario" th:readonly="${not imovel.novo}" th:field="*{inscricaoImobiliaria}" />
</div>
</div>
<div class="form-group tp-required" tp:classforerror="contribuinte.codigo">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="nomeContribuinte">Contribuinte</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="input-group">
<input type="text" id="nomeContribuinte" class="form-control" readonly="readonly" th:field="*{contribuinte.nome}"
placeholder="Clique na lupa para pesquisar o contribuinte" />
<input type="hidden" id="codigoContribuinte" th:field="*{contribuinte}" />
<span class="input-group-btn">
<button type="button" class="btn btn-default js-tooltip" title="Pesquisar"
data-toggle="modal" data-target="#pesquisaRapidaDeContribuintes" th:disabled="${not imovel.novo}">
<i class="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
</div>
</div>
<div class="form-group tp-required" tp:classforerror="condicaoDeResidente">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="condicaoDeResidente">Condição de Residente</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<select id="condicaoDeResidente" class="select2_single form-control" tabindex="-1" th:field="*{condicaoDeResidente}">
<option value="">Selecione uma condição</option>
<option th:each="condicaoDeResidente : ${condicoesDeResidencia}" th:value="${condicaoDeResidente}" th:text="${condicaoDeResidente.descricao}"></option>
</select>
</div>
</div>
<div class="form-group tp-required" tp:classforerror="situacao">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="situacao">Situação</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<select id="situacao" class="select2_single form-control" tabindex="-1" th:field="*{situacao}">
<option value="">Selecione uma situação</option>
<option th:each="situacao : ${situacoes}" th:value="${situacao}" th:text="${situacao.descricao}"></option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Status</label>
<div class="col-md-4 col-sm-4 col-xs-6">
<input type="checkbox" class="js-status" data-size="small"
data-on-color="primary" data-off-color="danger"
data-on-text="Ativo" data-off-text="Inativo"
data-inverse=true th:field="*{status}" />
</div>
<div class="col-md-5 col-sm-5 col-xs-6" th:unless="${imovel.novo}">
<button type="button" class="btn btn-success btn-sm js-valida-beneficio-btn" data:codigo="${imovel.codigo}" data:url="#{/beneficio}">Validar Benefício</button>
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
<button type="submit" class="btn btn-primary js-cancelar-btn">Cancelar</button>
<button type="submit" class="btn btn-success">Salvar</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<th:block th:replace="pesquisa-rapida/pesquisa-rapida-de-contribuintes :: pesquisaRapidaDeContribuintes"></th:block>
</section>
<th:block layout:fragment="javascript-extra">
<script th:src="#{/javascripts/vendors/handlebars.min.js}"></script>
<script th:src="#{/javascripts/contribuinte.pesquisa-rapida.js}"></script>
<script th:src="#{/javascripts/vendors/bootstrap-switch.min.js}"></script>
<script th:src="#{/javascripts/imovel.condeder-beneficio.js}"></script>
<script>
$(".js-status").bootstrapSwitch();
</script>
</th:block>
</html>
When I click on the button, the ajax request doesn't reach to the controller. The browser console shows error HTTP Status 400 - The request sent by the client was syntactically incorrect.
The followings are the request data.
Would anybody help me?
I want to send a variable from jQuery to my Servlet. Here is my jQuery:
<script>
$('#myModal').on('show.bs.modal', function(e) {
var metrics_key = $('.createAlarm').val();
var metrics_label = $(".createAlarm option:selected").text();
// Now you have the key and label in variables.
// Write the key into the textfield.
$('#myModal input[name="name"]').val(metrics_key);
// Change the HTML of an element to the label.
$('#myModal label[for="priority"]').html(metrics_label);
var val = $('#priority').text();
console.log(val);
$.post('/sampleapp/createAlarm', { val : val},
function() { // on success
alert("Insertion successful! of "+val);
})
.fail(function() { //on failure
alert("Insertion failed." +val);
});
});
</script>
On the servlet, I am using:
String Metric = request.getParameter("val");
Please find below the HTML Code. When I select a value from dropdown and click on Create Alarm button, the bootstrap modal pops up. I want to pass all those values from the popup to my servlet. I am able to do all that except the value I am setting in jQuery.
<div class="container" style="padding-top: 60px;" >
<select class="createAlarm" id="createAlarm" name="metrics">
<option value="cpuUsage">CPU Usage</option>
<option value="memoryUsage">Memory Usage</option>
<option value="diskRead">Disk Read</option>
<option value="diskWrite">Disk Write</option>
<option value="diskUsage">Disk Usage</option>
<option value="netUsage">Net Usage</option>
</select>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" data-whatever="Create Alarm">Create Alarm</button>
</div>
<!-- Modal- Create Alarm -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Create Alarm</h4>
</div>
<form action="/CMPE283_Project2/createAlarm" method="post" id="addcard" class="form-horizontal" role="form">
<div class="modal-body" style="height: 170px;">
<div class="form-group" style="height: 30px;">
<label for="title" class="col-md-3 control-label">Name</label>
<div class="col-md-9">
<input type="text" class="form-control" name="alarmName">
</div>
</div>
<div class="form-group" style="height: 30px; margin-bottom:30px;">
<label for="title" class="col-md-3 control-label">Description</label>
<div class="col-md-9">
<textarea class="form-control" name="desc"></textarea>
</div>
</div>
<div class="form-group">
<label for="priority" id="priority" name="priority" class="col-md-3 control-label">
<input type="text" class="form-control" name="name">
</label>
<div class="col-md-9">
<div class="col-md-3">
<select name="sign" class="form-control">
<option value="lessthan"><</option>
<option value="greaterthan">></option>
<option value="lessthanequalto"><=</option>
<option value="greaterthanequalto">>=</option>
</select>
</div>
<div class="col-md-3">
<input type="text" class="form-control" name="threshold">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button class="btn btn-primary" id="formSubmit" type="submit">Create Alarm</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
But i m getting null value for the Metric. Please help. Thanks.
insead of post try to use this way
$.ajax({
url : url,
type : "post",
data : values,
success : function(data) {
if (data.errorCode == "SUCCESS") {
} else {
}
},
error : function() {
alert("failure");
}
where values is you form or JSON
otherway try {"val" : val}
well i have got this Themeforest Template and played around with it until the website looks in a way how i imagined it. The only Problem i have is that the .js form somehow doesnt work and i dont have any idea. I dont even know where to tell the form to which Adress it should send the text. Maybe you can help me.
The Domain is: entwicklung.thechillingbull.de
This is the HTML:
<div class="container"> </div>
<div class="container"> </div>
<div class="bg-2 section" id="contact">
<div class="inner" data-topspace="50" data-bottomspace="20" data-image="flavours/coffeecream/images/demo-content/background-6.jpg">
<div class="container">
<h3 class="hdr4">Kontakt und Reservierung</h3>
<div class="easyBox full">
<div class="row nomargin">
<div class="col-md-11">
<h4 class="hdr2 special">Wenn du Uns etwas mitteilen oder Reservieren möchtest hast du hier die Chance!</h4>
<form class="simpleForm" action="form/form.php" method="post">
<fieldset>
<div class="form-group">
<label>Dein Name</label>
<input type="text" class="form-control" name="field_[]" placeholder="Schreibe deinen Namen">
</div>
<div class="form-group">
<label>Deine E-Mail-Adresse</label>
<input type="email" required class="form-control" name="email" placeholder="Schreibe deine E-Mail-Adresse">
</div>
<div class="form-group">
<label>Deine Nachricht</label>
<textarea class="form-control" rows="5" name="field_[]" placeholder="Schreibe deine Nachricht"></textarea>
</div>
<input type="hidden" name="msg_subject" value="Contact Form">
<input type="hidden" name="field_[]" value=" ">
<input class="btn btn-default" type="submit" value="Senden">
</fieldset>
</form>
<div class="successMsg" style="display:none;">Nachricht erfolgreich gesendet! </div>
<div class="errorMsg" style="display:none;"> Ups! Es ist ein Fehler unterlaufen, versuche es später erneut. </div>
</div>
<div class="col-md-2"> </div>
</div>
</div>
</div>
</div>
and this is the .js
/**
* Submitting Form
*/
jQuery(document).ready(function ($) {
var debug = false; //show system errors
var sendingMessage = 'Sending...';
$('.simpleForm').submit(function () {
var $f = $(this);
var $submit = $f.find('input[type="submit"]');
//prevent double click
if ($submit.hasClass('disabled')) {
return false;
}
$submit.attr('data-value', $submit.val()).val(sendingMessage).addClass('disabled');
$.ajax({
url: $f.attr('action'),
method: 'post',
data: $f.serialize(),
dataType: 'json',
success: function (data) {
if (data.errors) {
// error
var $errorMsg = jQuery($f).parent().find(".errorMsg");
jQuery($f).fadeOut(300,function(){
$errorMsg.fadeIn();
});
} else {
// success
var $successMsg = jQuery($f).parent().find(".successMsg");
jQuery($f).fadeOut(300,function(){
$successMsg.fadeIn();
});
}
$submit.val($submit.attr('data-value')).removeClass('disabled');
},
error: function (data) {
if (debug) {
alert(data.responseText);
}
$submit.val($submit.attr('data-value')).removeClass('disabled');
}
});
return false;
});
});
hope you can help me get this to work.
Thank you !
Change:
<form class="simpleForm" action="form/form.php" method="post">
To
<form class="simpleForm" action="/your-code-file" method="post">
where your-code-file will be the location of the file which will handle the form values.