While form submitting using ajax..getting Post not supported error ...don't know what is the error? - ajax

I am using form submission using AJAX in Spring MVC and Thymeleaf. When I try to submit it it shows
Post method is not supported
I can't figure out the mistake in my code:
<form class="form-horizontal" action="#" th:action="#{/teacher/teacherProfileUpdation}" th:object="${teacherProfileDetailsList}"
id="saveTeacherForm" method="POST" >
<br />
<div class="row">
<div class="col-lg-14 col-md-12">
<br />
<h5 style="margin-left: 15%;">Personal Details</h5>
<hr />
<div class="form-group">
<label class="col-sm-3 control-label">Name</label>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher first name" id="txtTeacherFname" th:field="*{firstName}" type="text" class="form-control" />
</div>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher middle name" id="txtTeacherMname" th:field="*{middleName}" type="text" class="form-control" />
</div>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher last name" id="txtTeacherLname" th:field="*{lastName}" type="text" class="form-control" />
</div>
</div>
</div>
<div class="col-lg-14 col-md-12">
<div class="form-actions">
<input type="hidden" id="hdnStudentByIdInSchoolAdmin" value="0" />
<input type="button" class="btn btn-info pull-right" id="btnUpdateTeacherProfile" value="Save" />
</div>
</div>
</div>
JS:
saveTeacherProfile :function(){
$("#saveTeacherForm").ajaxForm({
success : function(status) {
alert("success");
},
}).submit();
}
Controller:
#RequestMapping(value = "/updateTeacherProfile", method = RequestMethod.POST)
public String updateTeacherProfile( TeacherProfileDetails teacherProfileDetails){
System.out.println("-----------"+teacherProfileDetails.getFirstName()+"-------------");
System.out.println("-----------"+teacherProfileDetails.getLastName()+"-------------");
System.out.println("-----------"+teacherProfileDetails.getMiddleName()+"-------------");
return "success";
}

You are posting the form, but most likely your Spring controller is not configured to accept POST requests. Try this in your server-side Controller class for this page:
#RequestMapping(..., method = { RequestMethod.GET, RequestMethod.POST }, ...)
public void myControllerMethod()
{

#RequestMapping(..., method = { RequestMethod.GET, RequestMethod.POST }, ...)
public String updateTeacherProfile( TeacherProfileDetails teacherProfileDetails){
//ur Logic
}

Related

Model attribute inconsistent after form submission

I'm still trying to figure out what's happening on the backend here. Working with Spring Boot/Thymeleaf. I have a form template that updates a model attribute object on save. I'm trying to use the updated values on the backend, however it's inconsistent among my functions and I'm not sure why.
Thymeleaf template
<div layout:fragment="content" class="container">
<form action="#" th:action="#{/utility/exportbadges}" th:object="${badgeExport}" method="post">
<div class="form-group col-md-6">
<label class="col-form-label-sm">Badge type</label>
<select th:field="*{type}" class="form-control">
<option th:each="badgeType : ${T(org.myorg.myproject.model.badge.BadgeType).values()}"
th:value="${badgeType}"
th:text="${badgeType}">
</option>
</select>
</div>
<div class="form-group col-md-3">
<label class="col-form-label-sm">Use background?</label>
<input type="checkbox" th:field="*{background}" class="form-control">
</div>
<div class="form-group col-md-3">
<label class="col-form-label-sm">Mark preprinted?</label>
<input type="checkbox" th:field="*{preprinted}" class="form-control">
</div>
<div class="form-group col-md-3">
<label class="col-form-label-sm">Save to path (/tmp default):</label>
<input type="text" th:field="*{saveDir}" class="form-control" placeholder="/tmp">
</div>
<div class="form-group col-md-12 mt-2">
<div class="col-sm-10">
<input class="btn btn-primary" id="save" type="submit" value="Export" />
<input class="btn btn-secondary" type="reset" value="Reset" />
</div>
</div>
</form>
</div>
#RequestMapping(value = "/utility/exportbadges")
public String exportBadges(Model model) {
final BadgeExport badgeExport = new BadgeExport();
model.addAttribute("badgeExport", badgeExport);
return "utility/exportbadges";
}
POST method. The object is correct in this function. Any field that's edited in the form above reflects in this function. However, on redirect, the object is as if it only has default instantiation/has been unedited.
#RequestMapping(value = "/utility/exportbadges", method = RequestMethod.POST)
public String exportBadgeFlow(Model model,
#ModelAttribute("badgeExport") final BadgeExport badgeExport) {
log.info("BadgeExport badge type: {}", badgeExport.getType());
log.info("BadgeExport save dir pre export: {}", badgeExport.getSaveDir());
switch(badgeExport.getType()) {
case "Attendee":
log.error("Attendee export not yet implemented");
break;
case "Vip":
return "redirect:exportbadges/vip-badges.pdf";
case "Specialty":
return "redirect:exportbadges/specialty-badges.pdf";
case "Staff":
return "redirect:exportbadges/staff-badges.pdf";
case "Guest":
return "redirect:exportbadges/guest-badges.pdf";
}
return "redirect:exportbadges";
}
Redirect function. Badge type will be null and saveDir will be /tmp as default instead of updated value in form.
#RequestMapping(value = "/utility/exportbadges/vip-badges.pdf")
public ResponseEntity<String> getAllVipBadgePdf(#ModelAttribute("badgeExport") final BadgeExport badgeExport) throws IOException {
log.info("BadgeExport badge type: {}", badgeExport.getType());
log.info("BadgeExport save dir during export: {}", badgeExport.getSaveDir());
}

Validation of wrapper in spring form

I've wrapped two objects I wanted to use in one form. Here is the wrapper class:
public class UserCustomer {
User user;
Customer customer;
//Getters and setters
//Constructors
Controller:
#Controller
public class RegisterController {
#RequestMapping("/register")
public String showRegister(Model model){
model.addAttribute("userCustomer", new UserCustomer(new User(), new Customer()));
return "register";
}
#RequestMapping(value="/doRegister", method = RequestMethod.POST)
public String doRegister(Model model, #Valid UserCustomer userCustomer, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "register";
}
System.out.println(userCustomer.getUser());
return "registered";
}
}
And the form:
<h3 class="new-models">For New Customers</h3>
<div class="register">
<sf:form method="post" action="${pageContext.request.contextPath}/doRegister" commandName="userCustomer">
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div>
<span>First Name<label>*</label></span>
<sf:errors path="customer.name" cssClass="alert-danger"/>
<sf:input name="name" type="text" path="customer.name"/>
</div>
<div>
<span>Last Name<label>*</label></span>
<sf:errors path="customer.surname" cssClass="alert-danger"/>
<sf:input name="surname" type="text" path="customer.surname"/>
</div>
<div>
<span>Email Address<label>*</label></span>
<sf:errors path="user.email" cssClass="alert-danger"/>
<sf:input name="email" type="text" path="user.email"/>
</div>
<div>
<span>Username<label>*</label></span>
<sf:errors path="user.username" cssClass="alert-danger"/>
<sf:input name="username" type="text" path="user.username"/>
</div>
<div class="clearfix"> </div>
<!--a class="news-letter" href="#">
<label class="sf:checkbox">
<!--sf:input type="checkbox" name="newsletter" path="customer.newsletter" checked=""/><i> </i>Sign Up for Newsletter</label>
</a-->
<a class="news-letter" href="#"></a>
</div>
<div class="register-bottom-grid">
<h3>LOGIN INFORMATION</h3>
<div>
<span>Password<label>*</label></span>
<sf:errors path="user.password" cssClass="alert-danger"/>
<sf:input name="password" type="password" path="user.password"/>
</div>
<div>
<span>Confirm Password<label>*</label></span>
<sf:input type="password" path=""/>
</div>
</div>
<div class="clearfix"> </div>
<div class="register-but">
<input type="submit" value="register">
<div class="clearfix"> </div>
</div>
</sf:form>
</div>
Everything seems to be working fine, except for validation. I don't really know how to make validation in this wrapper.
Example validation for email in User class:
#Pattern(regexp = ".*\\#.*\\..*")
I have solved myself this problem, it's way more simple than I have expected it would be.
Validation works simply by adding #Valid annotation above user and customer fields in this wrapper, so that spring knows to actually validate them "deeper".

FormCollection parameter is empty while using #Ajax.BeginForm and html5 controls

I'm developing ASP.NET MVC5 project with boostrap, jquery, jquery UI. Submit is working fine but FormCollection in create Action is arriving empty in HomeController. I don't know what I'm doing wrong or is missing. PLease need help. Below snippet code.
Index.cshtml:
<div class="modal fade" id="modal" tabindex="-1" role="dialog">
<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">Empleado</h4>
</div>
<div class="modal-body">
#using (Ajax.BeginForm("Create", "Home", new AjaxOptions() { HttpMethod = "post" }, new { id = "dialog", name = "dialog" }))
{
<div class="panel">
<div class="panel-body">
<div class="form-group">
<label class="control-label">Nombres</label>
<input type="text" class="form-control" id="modalNombres" placeholder="Nombres" />
</div>
<div class="form-group">
<label class="control-label">Apellidos</label>
<input type="text" class="form-control" id="modalApellidos" placeholder="Apellidos" />
</div>
<div class="form-group">
<label class="control-label">Fecha de Nacimiento</label>
<input type="text" class="form-control" id="modalFechaNacimiento" placeholder="Fecha Nacimiento" />
</div>
<div class="form-group">
<label class="control-label">Tipo Documento</label>
<select class="form-control" id="modalTipoDocumento">
<option class="placeholder" selected disabled value="">--- Seleccione ---</option>
#foreach (var item in ViewBag.TiposDocumento)
{
<option value="#item.Id">#item.Descripcion</option>
}
</select>
</div>
<div class="form-group">
<label class="control-label">Número de Documento</label>
<input type="text" class="form-control" id="modalNumeroDocumento" placeholder="Número Documento" />
</div>
</div>
<div class="panel-footer">
<button type="button" role="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" role="button" class="btn btn-primary" id="btnGrabar">Grabar</button>
</div>
</div>
}
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
HomeController is:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
string nombres = collection["modalNombres"];
return RedirectToAction("Index");
}
catch
{
return View();
}
}
None of you <input> elements have name attributes so there is nothing sent to the server. Change
<input type="text" class="form-control" id="modalNombres" placeholder="Nombres" />
to
<input type="text" class="form-control" name="modalNombres" placeholder="Nombres" />
There is no need for id attributes unless you using javascript/jquery to refer to them.
However, I very strongly recommend you go to the MVC site and work through some basic tutorials and learn how to generate a view in MVC. You should have a model, use the strongly typed html helpers to bind to the properties of your model, and the POST method should have a parameter for the model so it is bound (you should never use FormCollection in MVC)
Note also, you using Ajax.BeginForm() which uses ajax to post the form values so return RedirectToAction("Index"); in your POST method is pointless. Ajax calls stay on the same page, they do not redirect.

Cannot submit a form on SpringMVC

I am fairly new to SpringMVC and have a form that can not submit to the back-end. I created the form as following and when I submit it error 404 will be returned. I changed action to /MyProject/contact but did not work.
<form class="form-horizontal" role="form" method="post"
action="/contact">
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Name
</label> <input type="text" class="form-control" id="name"
name="name" placeholder="Your name" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Email
Address</label> <input type="email" class="form-control" id="email"
name="email" placeholder="Your email" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Phone
Number</label> <input type="number" class="form-control" id="phone"
name="phone" placeholder="Phone number" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Enquiry</label>
<textarea class="form-control" rows="4" name="message"
placeholder="Please enter your enquiry"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-2 " style="float: right;">
<input id="submit" name="submit" type="submit" value="Send"
class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<! Will be used to display an alert to the user>
</div>
</div>
</form>
Controller
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
Error
HTTP Status 404 - /contact
type Status report
message /contact
description The requested resource is not available.
Its beacuse spring does not know how to pass the param Contact contact to your controller method. You need to do couple of things to make it work. Change your form to like below.
<form class="form-horizontal" role="form" method="post" modelAttribute="contact" action="/contact">
Your controller to take contact as model attribute.
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(#ModelAttribute Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
For a better understanding of what a model attribute does, there are plenty of samples and explanation online. Hope this helps.
I could solve the problem by help of minion's answer, following this tutorial and adding following link
#RequestMapping(value = "/contact", method = RequestMethod.GET)
public ModelAndView contactForm() {
System.err.println("here in GET");
return new ModelAndView("contact", "command", new Contact());
}

Spring MVC: Multiple Models in A form: Binding problems and blank screen

I want combine 2 model(users and userData) for get Request Params but as a result i saw a blank screen. what is problem in my code?
Register object is a ModelAttribute
users and userData models have some fields.
Data Models
public class Register {
private Users users;
private UserData userData;
//getters and setters
}
register.jspx
<form:form action="register" method="post" commandName="register">
<fieldset>
<div class="span12">
<legend>Sign Up as a Merchant</legend>
</div>
<form:input type="hidden" path="enabled" value="true"/>
<div class="span6">
<div class="control-group" id="usernameCtl">
<label class="control-label" for="username">Username</label>
<div class="controls">
<form:input type="text" class="input-xlarge" id="username" path="users.username"/>
<form:errors path="users.username"/>
</div>
</div>
<div class="control-group" id="passwordCtl">
<label class="control-label" for="password">Password</label>
<div class="controls">
<form:input type="password" class="input-xlarge" id="password" path="users.password"/>
<form:errors path="users.password"/>
</div>
</div>
<div class="control-group" id="confirmCtl">
<label class="control-label" for="confirm">Confirm</label>
<div class="controls">
<form:input type="password" class="input-xlarge" id="confirm" name="confirm"/>
</div>
</div>
<div class="control-group" id="emailCtl">
<label class="control-label" for="email">Email</label>
<div class="controls">
<form:input type="text" class="input-xlarge" id="email" path="userData.email"/>
<form:errors path="userData.email"/>
</div>
</div>
</div>
<div class="span6">
<div class="control-group" id="nameCtl">
<label class="control-label" for="name">Name</label>
<div class="controls">
<form:input type="text" class="input-xlarge" id="name" path="userData.name"/>
<form:errors path="userData.name"/>
</div>
</div>
<div class="control-group" id="surnameCtl">
<label class="control-label" for="surname">Surname</label>
<div class="controls">
<form:input type="text" class="input-xlarge" id="surname" path="userData.surname"/>
<form:errors path="userData.surname"/>
</div>
</div>
<div class="control-group" id="IDNumberCtl">
<label class="control-label" for="streetAddress">Id Number</label>
<div class="controls">
<form:input type="text" class="input-xlarge" id="idNumber" path="userData.idNumber"/>
<form:errors path="userData.idNumber"/>
</div>
</div>
<div class="control-group" id="FactoryCtl">
<label class="control-label" for="city">Factory</label>
<div class="controls">
<form:select path="userData.factory">
<form:options itemValue="id" itemLabel="name" items="${factory}" />
</form:select>-->
</div>
</div>
<div class="control-group" id="IssueSectionCtl">
<label class="control-label" for="state">IssueSection</label>
<div class="controls">
<form:select path="userData.issueSection">
<form:options itemValue="id" itemLabel="name" items="${issueSection}" />
</form:select>-->
</div>
</div>
<input class="btn btn-primary btn-large" type="submit" value="Register"/>
Cancel
</div>
</fieldset>
</form:form>
UsersController_Roo_Controller
#RequestMapping(method = RequestMethod.POST, produces = "text/html",value = "/register")
public String UsersController.register(#ModelAttribute("register") Register register, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
if (bindingResult.hasErrors()) {
populateRegisterForm(uiModel, register);
return "userses/register";
}
uiModel.asMap().clear();
//users.setUserData(userData);
register.getUsers().persist();
return "redirect:/userses/" + encodeUrlPathSegment(register.getUsers().getId().toString(), httpServletRequest);
}
#RequestMapping(params = "register", produces = "text/html")
public String UsersController.registerForm(Model uiModel) {
populateRegisterForm(uiModel, new Register());
return "userses/register";
}
void UsersController.populateRegisterForm(Model uiModel, Register register) {
uiModel.addAttribute("factory", Factory.findAllFactorys());
uiModel.addAttribute("issueSection", IssueSection.findAllIssueSections());
uiModel.addAttribute("register",register);
}
I solved problem..
in
<input class="btn btn-primary btn-large" type="submit" value="Register"/>
I converted to  
and problem solved.

Resources