Spring MVC ajax post text data - ajax

I have a form:
<form name="employeeForm" method="post">
<table cellpadding="0" cellspacing="0" border="1" class="GridOne">
<tr>
<td>First Name</td>
<td><input type="text" name="firstName" id="firstName" value="" onchange="FirstNameAjaxCall(event);"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastName" id="lastName" value=""></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" id="email" value=""></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" value="Ajax Submit" onclick="madeAjaxCall(event);"></td>
</tr>
</table>
</form>
//====================================================
and my controller:
#RequestMapping(value="/ajaxExample", method=RequestMethod.POST)
public #ResponseBody ModelAndView firstnameAjaxTest(#RequestParam(value="text") String text) {
final ModelAndView modelAndView = new ModelAndView();
System.out.println(text);
modelAndView.setViewName("ajaxExample");
return modelAndView;
}
//===============================================
and script
function FirstNameAjaxCall(e){
e.preventDefault();
var text = document.getElementById('firstName').value;
alert(text);
$.ajax({
type: "POST",
url: "http://localhost:8080/ajaxExample",
cache: false,
dataType: 'text',
data:{
text:text
},
success: function(){
alert('Done');
},
error: function(){
alert('Error while request..');
}
});
return false;
return false;
}
And request return msg: Error while request..
I doesn understand why.
Please help me

Related

Spring Boot doesnt return template in Post Mapping

I hope some of you have an idea about this. I'm still new to Spring but till this point I could figured out every problem myself. I'm using also Thymeleaf for the templates.
In the Controller the function for #GetMapping works as intended, but the #PostMapping function doesnt return the template which I specified in the return parameter and so the browser shows the wrong page.
The #PostMapping function gets triggered by the ajax statement in the html script.
I get no errors or warnings on server side as well as on client side. So I have no idea were the spot the mistake.
Hope some of you can spot the mistake. Thanks in advance anyway.
Controller:
#Controller
public class SpringController {
#RequestMapping(value="/tank", method = RequestMethod.GET)
public String loadData(Model model){
Tankstelle[] data = TankerAPI.getTankData(lat, lng, 5, sort, type);
model.addAllAttributes(convertdata("name", data));
model.addAllAttributes(convertdata("dist", data));
model.addAllAttributes(convertdata("price", data));
return "home";
}
#RequestMapping(value = "/tank", method = RequestMethod.POST)
public String getChangedData(#RequestBody JSONObject incomingjson) {
lat = Float.parseFloat(incomingjson.get("lat").toString());
lng = Float.parseFloat(incomingjson.get("lng").toString());
BigDecimal biglat = new BigDecimal(lat).setScale(3, RoundingMode.HALF_UP);
BigDecimal biglng = new BigDecimal(lng).setScale(3, RoundingMode.HALF_UP);
lat = biglat.floatValue();
lng = biglng.floatValue();
sort = "price"; //for seeing a difference
System.out.println(incomingjson.get("lat")+" "+incomingjson.get("lng"));
return "test"; //here it should return the template "test" but it return "home"
}
home.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
<meta charset="UTF-8"/>
<title>guenstigertanken.de</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>...
</style>
</head>
<body onload="getLocation()">
<div class="ueberschriftbox"></div>
<h2 class="header">guenstigertanken.de</h2>
<h2 class="subheader">Wir finden die günstigsten Spritpreise für Sie</h2>
<div class="backrounding">
<div class="steuerelementebox"></div>
<div class="steuerelementespritsorteueberschrift">
<h2>Spritsorte</h2>
<label class="container1">Super E5
<input type="radio" id="E5" name="radio1" onclick="autoSubmit()">
<span class="checkmark1"></span>
</label>
<label class="container1">Super E10
<input type="radio" id="E10" name="radio1" onclick="autoSubmit()">
<span class="checkmark1"></span>
</label>
<label class="container1">Diesel
<input type="radio" id="Diesel" name="radio1" onclick="autoSubmit()">
<span class="checkmark1"></span>
</label>
</div>
<div class="steuerelementesortierennachueberschrift">
<h2>Sortieren nach</h2>
<label class="container2">Preis aufsteigend
<input type="radio" checked="checked" name="radio2" onclick="autoSubmit()">
<span class="checkmark2"></span>
</label>
<label class="container2">Preis absteigend
<input type="radio" name="radio2" onclick="autoSubmit()">
<span class="checkmark2"></span>
</label>
<label class="container2">Distanz aufsteigend
<input type="radio" name="radio2" onclick="autoSubmit()">
<span class="checkmark2"></span>
</label> <label class="container2">Distanz absteigend
<input type="radio" name="radio2" onclick="autoSubmit()">
<span class="checkmark2"></span>
</label>
<label class="container2" id="alph">Name alphabetisch
<input type="radio" name="radio2" onclick="autoSubmit()">
<span class="checkmark2"></span>
</label>
</div>
<div class="buttonsbox"></div>
<div class="tabellenbox"></div>
<div class="ueberuns">
<p>Über uns</p>
</div>
<div class="agb">
<p>AGB</p>
</div>
<div class="datenschutz">
<p>Datenschutz</p>
</div>
<div class="impressum">
<p>Impressum</p>
</div>
<div class="left show">
<table id="datatable">
<thead>
<tr> <th>Name</th> <th>Entfernung</th> <th>Preis</th> <th>Favorit</th> </tr>
</thead>
<tbody>
<tr> <td th:text="${name1}">AGIP</td> <td th:text="${dist1}">7km</td> <td th:text="${price1}">1,20€</td> <td><input type="checkbox"></td> </tr>
<tr> <td th:text="${name2}">Aral</td> <td th:text="${dist2}">12km</td> <td th:text="${price2}">1,23€</td> <td><input type="checkbox"></td> </tr>
<tr> <td th:text="${name3}">Esso</td> <td th:text="${dist3}">2km</td> <td th:text="${price3}">1,25€</td> <td><input type="checkbox"></td> </tr>
<tr> <td th:text="${name4}">Esso</td> <td th:text="${dist4}">10km</td> <td th:text="${price4}">1,25€</td> <td><input type="checkbox"></td> </tr>
<tr> <td th:text="${name5}">Esso</td> <td th:text="${dist5}">5km</td> <td th:text="${price5}">1,25€</td> <td><input type="checkbox"></td> </tr>
<tr> <td th:text="${name6}">BP</td> <td th:text="${dist6}">13km</td> <td th:text="${price6}">1,35€</td> <td><input type="checkbox"></td> </tr>
<tr> <td th:text="${name7}">BP</td> <td th:text="${dist7}">13km</td> <td th:text="${price7}">1,35€</td> <td><input type="checkbox"></td> </tr>
<tr> <td th:text="${name8}">BP</td> <td th:text="${dist8}">13km</td> <td th:text="${price8}">1,35€</td> <td><input type="checkbox"></td> </tr>
</tbody>
</table>
</div>
</div>
<a class="cssbuttonfavoriten" href="test.html">Favoriten></a>
<a class="cssbuttonleaderboard" href="test.html">Leaderboard></a>
<a class="cssbuttonstatistiken" href="test.html">Statistiken></a>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
}
}
function showPosition(position) {
var posdata = '{"lat":"'+position.coords.latitude+'","lng":"'+position.coords.longitude+'","typeselect":"'+type+'"}';
$.ajax({
type: 'post',
url: '/tank',
data: JSON.stringify(posdata),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function(posdata) {
//alert("ajax success: refresh page to sort after price[prob current setting]")
},
error: function(){
alert("ajax error")
}
});
}
</script>
</body>
</html>
When you make any request through ajax you just receive corresponding response in your callback function:
success: function(posdata) {
//alert("ajax success: refresh page to sort after price[prob current setting]")
},
So browser will not show you a new template page. Your page is in "postdata" response

Getting validation error after successful form submit

I am using angular 8 with angular material 7. I am using reactive form for creating and submiting forms. After form submit, I am programatically reseting the form and aslo marking as untouchewd. But after every submit, I am seeing all validation trigerring and reds al over
export class RegisterUserComponent implements OnInit{
createUserForm: FormGroup;
allRolesList: Array<UserRole>;
assignedRoles: Array<UserRole>[];
assignedRolesChanged = new Subject<Array<UserRole>>();
newUser: GetUserResponse;
constructor(private roleService: RoleService, private userService: UsersService) {
this.roleService.allRolesListChanged.subscribe((res: Array<UserRole>)=>{
this.allRolesList = res;
});
this.userService.newUserCreated.subscribe((res: GetUserResponse)=>{
this.newUser = res;
this.createUserForm.reset(true);
this.createUserForm.markAsUntouched({onlySelf: true});
});
}
async ngOnInit() {
this.roleService.getAllRoles();
this.initForm();
}
initForm(){
this.createUserForm = new FormGroup({
loginId: new FormControl(null, [Validators.required, Validators.email]),
firstName: new FormControl(null, Validators.required),
lastName: new FormControl(null, Validators.required),
userRoles: new FormControl(null)
});
}
onSubmit(){
let data = this.createUserForm.value;
console.log(data);
let req: UserRequest = {
loginId: data.loginId ? data.loginId.trim() : undefined,
firstName:data.firstName ? data.firstName.trim() : undefined,
lastName:data.lastName ? data.lastName.trim() : undefined,
assignedRoles: {userRoles:data.userRoles}
};
console.log(req);
this.userService.registerNewUser(req);
}
}
HTML template for for is very simple like this:
<div class="large-box mat-elevation-z4">
<form id="simple-form-input" class="search-container" [formGroup]="createUserForm" (ngSubmit)="onSubmit()">
<table>
<tbody>
<tr>
<td>
</tr>
</tbody>
</table>
<table cellspacing="0" cellpadding="5">
<tbody>
<tr>
<td>
<mat-form-field>
<mat-label>Login ID</mat-label>
<input matInput formControlName="loginId" type="text" name="loginId" placeholder="Login ID">
</mat-form-field>
</td>
</tr>
<tr>
<td>
<mat-form-field>
<mat-label>First Name</mat-label>
<input matInput formControlName="firstName" type="text" name="firstName"
placeholder="First Name">
</mat-form-field>
</td>
</tr>
<tr>
<td>
<mat-form-field>
<mat-label>Last Name</mat-label>
<input matInput formControlName="lastName" type="text" name="lastName"
placeholder="Last Name">
</mat-form-field>
</td>
</tr>
<tr>
<td>
<mat-form-field>
<mat-label>Access Privileges</mat-label>
<mat-select formControlName="userRoles" name="userRoles" multiple>
<mat-option *ngFor="let userRole of allRolesList" [value]="userRole">
{{userRole.name}}
</mat-option>
</mat-select>
</mat-form-field>
</td>
</tr>
<tr>
<td>
<button [disabled]="!createUserForm.valid" type="submit" color="primary" mat-raised-button>Submit</button>
</td>
</tr>
</tbody>
</table>
</form>
</div>
It's not enough to set the controls to untouched, you need to clear out the errors in the controls which occur when you reset due to Validators.required:
this.createUserForm.reset();
Object.keys(this.createUserForm.controls).forEach(
key => this.createUserForm.controls[key].setErrors(null)
);
this.createUserForm.markAsUntouched({onlySelf: true});

Ajax form redirect to another url

i want to redirect to another url when the form is submitted how can i do it
i am new to ajax so please tell where to add the code which can do it
here is my code
<script type="text/javascript">
function submitForm() {
if ($("#fields_fname").val() == "") {
$("#fields_fname").focus();
alert("The First Name field is required.");
return false;
}
if ($("#fields_lname").val() == "") {
$("#fields_lname").focus();
alert("The Last Name field is required.");
return false;
}
if ($("#fields_email").val() == "") {
$("#fields_email").focus();
alert("The Email field is required.");
return false;
}
if ($("#fields_phone").val() == "") {
$("#fields_phone").focus();
alert("The Phone field is required.");
return false;
}
if ($("#fields_zip").val() == "") {
$("#fields_zip").focus();
alert("The Postal Code field is required.");
return false;
}
if ($("#fields_suffix").val() == "") {
$("#fields_suffix").focus();
alert("The 'I'm Interested In' field is required.");
return false;
}
$.ajax({
url: 'zohoprocess.php',
type:'POST',
data:$('#ContactForm').serialize(),
success: function(){
$(".form_result").html('Form 1 submitted successfully');
$.ajax({
url: 'https://app.icontact.com/icp/signup.php',
type:'POST',
data:$('#ContactForm').serialize(),
success: function(){
$(".form_result").html('Form 2 submitted successfully');
},
error:function(){
alert("success");
$(".form_result").html('');
return false;
}
});
},
error:function(){
alert("failure");
$(".form_result").html('');
return false;
}
});
return false;
}
</script>
<form id="ContactForm">
<input type="hidden" name="redirect" value="http://tennispronow.com/thanks.html">
<input type="hidden" name="errorredirect" value="http://www.icontact.com/www/signup/error.html">
<div id="SignUp">
<table width="260" class="signupframe" border="0" cellspacing="0" cellpadding="5">
<tr>
<td valign="top" align="right">
<span class="required">*</span>Email
</td>
<td align="left">
<input type="text" name="fields_email" id="fields_email">
</td>
</tr>
<tr>
<td valign="top" align="right">
<span class="required">*</span>First Name
</td>
<td align="left">
<input type="text" name="fields_fname" id="fields_fname">
</td>
</tr>
<tr>
<td valign="top" align="right">
<span class="required">*</span>Last Name
</td>
<td align="left">
<input type="text" name="fields_lname" id="fields_lname">
</td>
</tr>
<tr>
<td valign="top" align="right">
<span class="required">*</span>What Level Player are you?
</td>
<td align="left">
<select name="fields_prefix" id="fields_prefix">
<option></option>
<option value="Beginner">Beginner</option>
<option value="Upper Beginner">Upper Beginner</option>
<option value="Intermediate">Intermediate</option>
<option value="Advanced">Advanced</option>
</select>
</td>
</tr>
<tr>
<td valign="top" align="right">
<span class="required">*</span>I am Interested in:
</td>
<td align="left">
<select name="fields_suffix" id="fields_suffix">
<option></option>
<option value="Private Lessons">Private Lessons</option>
<option value="Lessons & Equipment">Lessons & Equipment</option>
<option value="Classes">Classes</option>
<option value="Equipment">Equipment</option>
</select>
</td>
</tr>
<tr>
<td valign="top" align="right">
<span class="required">*</span>Other Info:
</td>
<td align="left">
<input type="text" name="fields_fax" id="fields_fax">
</td>
</tr>
<tr>
<td valign="top" align="right">
<span class="required">*</span>Phone
</td>
<td align="left">
<input type="text" name="fields_phone" id="fields_phone">
</td>
</tr>
<tr>
<td valign="top" align="right">
<span class="required">*</span>Postal Code
</td>
<td align="left">
<input type="text" name="fields_zip" id="fields_zip">
</td>
</tr>
<input type="hidden" name="listid" value="42670">
<input type="hidden" name="specialid:42670" value="D1CQ">
<input type="hidden" name="clientid" value="860526">
<input type="hidden" name="formid" value="4668">
<input type="hidden" name="reallistid" value="1">
<input type="hidden" name="doubleopt" value="0">
<tr>
<td></td>
<td><span class="required">*</span> = Required Field</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Submit" onClick="return submitForm()">
</td>
</tr>
</table>
<div class="form_result"> </div>
</div>
</form>
please check it dont know what to write more
Just add action attribute to the form tag.

Safari, MVC3 ajax form submit

I have a form that submits just fine in FF, IE 8, IE 9, chrome.
In safari (windows), it submits but my model is empty. This behavior is only on my dev and prod site, not local development. Local development works normal. What am i doing wrong here?
Form:
<form action="/NetSite/Applications/ElectronicFileTransfer" id="TransfersSearchForm" method="post">
<table class="siteTable">
<tbody>
<tr>
<th style="width: 20%;">FICE</th>
<td style="width: 80%;"><input id="Criteria_Fice" maxlength="6" name="Criteria.Fice" size="6" type="text" value="" /></td>
</tr>
<tr>
<th>Source Email</th>
<td><input id="Criteria_SourceEmail" maxlength="40" name="Criteria.SourceEmail" size="25" type="text" value="" /></td>
</tr>
<tr>
<th>Target Email</th>
<td><input id="Criteria_TargetEmail" maxlength="100" name="Criteria.TargetEmail" size="25" type="text" value="" /></td>
</tr>
<tr>
<th>Upload From Date</th>
<td>
<input class="datePicker" data-val="true" data-val-date="Invalid date specified. Date should be like MM/DD/YYYY." id="Criteria_FromDate" maxlength="12" name="Criteria.FromDate" size="12" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Criteria.FromDate" data-valmsg-replace="true"></span>
</td>
</tr>
<tr>
<th>Upload To Date</th>
<td>
<input class="datePicker" data-val="true" data-val-date="Invalid date specified. Date should be like MM/DD/YYYY." id="Criteria_ToDate" maxlength="12" name="Criteria.ToDate" size="12" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Criteria.ToDate" data-valmsg-replace="true"></span>
</td>
</tr>
<tr>
<th class="empty"></th>
<td>
<button type="submit" title="Search" id="SubmitButton" class="gradientbutton gradientsmall gradientorange">Search</button>
<button type="button" title="Clear" id="ClearButton" class="gradientbutton gradientsmall gradientorange">Reset</button>
</td>
</tr>
</tbody>
</table>
</form>
JS submit method called by the event:
searchFormSubmit: function ($form, currentForm) {
if ($form.valid()) {
var $button = $("#" + FileTransferHome._enum.SubmitButton);
var $searchResults = $("#" + FileTransferHome._enum.SearchResultsDivId);
jMessage("Processing request...", $button, true, false);
$.ajax({
cache: false,
url: currentForm.action,
type: currentForm.method,
data: $form.serialize(),
error: function (xhr, ajaxOptions, thrownError) {
jMessageHide();
$searchResults.html(xhr.responseText).addClass(JSGlobalVars.MessageBoxError).fadeIn('slow');
},
success: function (result) {
jMessageHide();
$searchResults.removeClass(JSGlobalVars.MessageBoxError).html(result).fadeIn('slow');
location.hash = "SEARCHRESULTS";
}
});
}
}
Action:
I have an else block in there that i have put in just to test this case and it executes rather than the main block.
[HttpPost]
public ActionResult Index(ElectronicFileTransferHomeViewModel model)
{
... actions...
}
This in as internal app and behind windows login. Safari has a non issue with with windows authentication.
A work around that seems to be working for us (although not ideal) is to put Safari in Private browsing mode.

ajax login in yii framework

I have new homepage with login and register with unlogin user.
homepage.php
<script type="text/javascript" >
$(document).ready(function()
{
$("#btnLogin").click(function()
{
var username= $("#usernamelogin").val();
var password=$("#passwordlogin").val();
var remember = $("#rememberlogin").is(':checked');
var dataString = 'usernamelogin='+ username + '&passwordlogin=' + password + '&rememberlogin=' + remember;
$.ajax
({
type: "POST",
url: "homepage",
data: dataString,
cache: false,
success: function(html)
{
alert(html);
}
});
});
});
</script>
<form action="" method="post" name="frmLogin" class="Login">
<table width="960px" align="center">
<tr>
<td rowspan="3" width="404"><label id="lbbanner"><b>UIT SOCIAL NETWORK</b></label></td>
<td width="216"><label>Username:</label></td>
<td width="324">Password:</td>
</tr>
<tr>
<td><input type="text" witdth="200px" id ="usernamelogin" name="txtUsernameLogin" /></td>
<td><input type="password" width="200px" id="passwordlogin" name="txtPasswordLogin" /></td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" id="rememberlogin" name="checkRemember" /> Remember me!
<input type="button" value="Log in" id="btnLogin" name="Login"/></td>
<td colspan="2" align="right"></td>
</tr>
<tr>
</tr>
</table>
</form>
In SiteController I have actionHomePage()
public function actionHomePage() {
$model = new LoginForm();
$model->username = $_POST['usernamelogin'];
$model->password = $_POST['passwordlogin'];
$model->rememberMe = $_POST['rememberlogin'];
//echo $model->errors;
print_rcount(($model->getErrors()));
//echo $model->username . "&&" . $model->password . "$$" .$model->rememberMe;
// validate user input and redirect to the previous page if valid
if ($model->validate() && $model->login()) {
$this->loginStatus = true;
//$this->redirect(Yii::app()->user->returnUrl);
echo "SUCCESS";
} else {
echo "Error";
}
}
When I fill username and password with correct info but it return "ERROR"
$model->validate() is false but I have correct info.
I dont know what i am wrong in this part.
Your input variable names need to match the POST variables you are querying so
<td><input type="text" witdth="200px" id ="usernamelogin" name="txtUsernameLogin" /></td>
<td><input type="password" width="200px" id="passwordlogin" name="txtPasswordLogin" /></td>
should be like this:
<td><input type="text" witdth="200px" id ="usernamelogin" name="usernameLogin" /></td>
<td><input type="password" width="200px" id="passwordlogin" name="passwordLogin" /></td>
same for rememberlogin
because in actionHomePage() : $model->rememberMe = true or false; $_post return a string . You try :
($_POST['rememberlogin'] == "false") ? $model->rememberMe = false : $model->rememberMe = true ;

Resources