I'm having a trouble when posting a form with AJAX.
Here is my ajax call:
function submit() {
$.ajax({
type: "POST",
url: "http://localhost:8080/executeRetrieve",
data: $("#form").serialize(),
dataType: "json",
success: function(data) {
alert(data);
}
})
}
And here is my HTML form (They're in the same page):
<form id="form" method="post">
User <input type="text" name="user" id="user"/><br />
Password <input type="password" name="password" id="password"/><br />
<input type="submit" value="Submit" onclick="submit()"/>
And also, this is my action:
#RequestMapping(value = "/executeRetrieve", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
public #ResponseBody String executeRetrieve(HttpServletRequest request) {
JSONObject json = new JSONObject();
json.put("message", "hello");
return json.toString();
}
I'm confused. Shouldn't that work? I've been searching for a solution for at least 3 days and I can't get to understand what's happening. The action method isn't even being reached. Would someone know where I am making a mistake?
Thanks in advance, pals.
I think there is issue in URI that you are trying to call from ajax http://localhost:8080/executeRetrieve. It should contains the application name deployed in server as well. e.g. http://localhost:8080/<app_name>/executeRetrieve
Related
I try to send form data through thymeleaf + ajax to Java Controller.
But at ReplyDto, can't receive data.
This is my code.
Themeleaf, Ajax .html
function insertReply() {
$.ajax({
type: 'POST',
url: '/reply/insertReply',
data: $("#replyForm").serialize(),
contentType: "application/json",
success: function(data) {
alert("test");
},
error: function(request, status, error) {
alert("Error : " + error + "\nStatus : " + status + "\nRequest : " + request);
}
});
}
<form id="replyForm" th:object="${replyDto}" th:method="post">
<input type="hidden" th:field="${post.postNo}" th:value="${post.postNo}">
<input class="form-control" type="text" th:field="*{replyTitle}" placeholder="replyTitle">
<textarea class="form-control" th:field="*{replyContent}" placeholder="insert" id="replyContentData" style="height: 100px"></textarea>
<button class="btn btn-primary" id="replyInsertButton" type="button" onclick='insertReply()'>댓글 입력</button>
</form>
ReplyDto.java
private int replyNo;
private String replyTitle;
private String replyContent;
private int postNo;
ReplyContoller.java
#PostMapping("/insertReply")
public int insertReply(ReplyDto replyDto) {
System.out.println(replyDto.getPostNo());
System.out.println(replyDto.getReplyTitle());
System.out.println(replyDto.getReplyContent());
return replyService.insertReply(replyDto);
}
Controller has annotation #RestController.
At console, log 0, null, null each postNo, replyTitle, replyContent.
How can I get form data to Controller?
Please help!
Your are missing #RequestBody
public int insertReply(#RequestBody ReplyDto replyDto) { ...
$("#replyForm").serialize() turns form into query string. You need valid JSON
You should probably go for a solution like this: Spring RestController POST accepting a basic HTML form
If you insist on proceeding with your current solution:
Start with verifying controller in Postman when fixed missing #RequestBody.
Converting form to JSON:
https://www.learnwithjason.dev/blog/get-form-values-as-json/
https://medium.com/#mwakatumbula_/code-15ecdb18c2ef
https://css-tricks.com/snippets/jquery/serialize-form-to-json/
Suppose I have a Login Object, when I make a get request for 'login', I send the Login object and in the JSP Page I use model attribute and paths to map the attributes as follows:
ViewController:
#GetMapping("/login")
public String login(Model model){
Login login = new Login();
model.addAttribute("login",login);
return "login";
}
JSP Page:
...
<form:form action="login" method="post" modelAttribute="login">
<form:hidden path="id"/>
<label for="username">UserName</label>
<form:input path="username"/><br>
<label for="password">Password</label>
<form:password path="password"/><br>
<form:button>Login</form:button>
</form:form>
...
Now when I hit on the Login Button, the login object is sent to the appropriate controller and it returns a ResponseEntity Object accordingly with some message.Once the processing is done, the page refreshes and the message in the ResponseEntity object is displayed, say "Login Successful".
But I want to display this message in the form of an alert.
To do that I'll have to make an AJAX request and upon success call the alert with the message, but in this approach I can no longer use the modelAttribute and AJAX has so sent a Login object, would that be possible?
Is there any way to use the functionality of the modelAttribute and also making AJAX requests?
After digging up for details about the same, I finally got the solution!
I had to make the following changes.
Login.jsp - Add a new button tag outside the tag
...
<form:form id="myform" action="login" method="post" modelAttribute="login">
<form:hidden path="id"/>
<label for="username">UserName</label>
<form:input path="username"/><br>
<label for="password">Password</label>
<form:password path="password"/><br>
</form:form>
<button id="login-btn">Login</button>
...
AJAX Script:
$(document).ready(function () {
$("#login-btn").click(function () {
$.ajax({
type: "POST",
url: "login",
data : $("#myform").serialize(),
success: function (data) {
alert(data);
},
error: function(data){
alert(data);
}
});
})
});
Controller:(to check if the login was valid or not)
#PostMapping("/login")
public ResponseEntity<?> login(#ModelAttribute("login") Login login){
boolean status = loginDao.isValidLogin(login);
String message = (status)?"Login Succcessful":"Incorrect Login Credentials!";
return new ResponseEntity<>(message,HttpStatus.OK);
}
I am having a few input fields in my jsp page that get a Cyrillic input which I am then upon pressing a button trying to send to this java method using ajax. The strings in the java method end up being gibberish.
The fields in the jsp page:
<div class="span1">
<form:label cssClass="control-label" path="">
<spring:message code="web.messages.someMessage" />
</form:label>
<form:input cssClass="input-block-level" path="" id="articleId" />
</div>
<div class="span1">
<label> </label>
<button type="button" id="search-btn" class="btn" >
<spring:message code="web.messages.buttonMessage" />
</button>
</div>
The ajax in the script:
$("#search-btn").on("click", function(e) {
e.preventDefault();
showDialog("${pageContext.request.contextPath}");
});
function showDialog(baseContext) {
var article = $('#articleId').val().replace(/\s+/g, "");
if (article) {
article = "?article=" + article;
}
$.ajax({
type : "GET",
url : "${pageContext.request.contextPath}/sync/getFilter"
+ article,
success : function(data) {
onClickTable();
}
});
}
This is part of the java method, where the value turns into gibberish:
#RequestMapping(value = "/getFilter", method = RequestMethod.GET)
public #ResponseBody ModelAndView getFilter(HttpServletRequest request) {
String article = (String) request.getParameter("article");
.
.
Fixed the problem by putting the information in a JSON and sending it like that.
The changed made:
The ajax in the script part of the jsp:
function showDialog(baseContext) {
var article = $('#articleId').val().replace(/\s+/g, "");
var data = {
"article": $('#articleId').val().replace(/\s+/g, ""),
// other keys and values
"lastKey": $('#lastValueId').val().replace(/\s+/g, "")
}
$.ajax({
type : "POST",
url : "${pageContext.request.contextPath}/sync/getFilter",
data: data,
success : function(data) {
onClickTable();
}
});
}
The java method handling the data:
#RequestMapping(value = "/getFilter", method = RequestMethod.POST)
public #ResponseBody ModelAndView getFilter(SomeObject receivedData) {
String article = receivedData.getArticle();
// rest of the method
Where SomeObject is an object containing the values that we receive in the data with proper set and get methods for them.
Ajax code:
var str = $("#observationForm").serialize();
$.ajax({
type : "post",
data : str,
url : "updateObservation",
async : true,
/* dataType : "multipart/form-data", */
success : function() {
alert("success");
}
});
JSP-Spring Form :
<form:form modelAttribute="ObservationModal" action="updateObservation" id="observationForm">
<label class="control-label">Tooth No</label>
<input type="text" class="form-control" name="tooth" id="tooth" placeholder="Enter tooth no" />
<label class="control-label">Uploaded file(PDF)</label>
<input type="file" class="form-control" name="attachment" value="" id="attachment" placeholder="" />
<input type="button" value="Save" onclick="updateObservation();" />
</form:form>
Controller Class
#RequestMapping(value = "/updateObservation", method = RequestMethod.POST)
public #ResponseBody String updateObservation(
#ModelAttribute("ObservationModal") ObservationModal formObj) {
String result = "";
System.out.println(":" + formObj.getTooth());
System.out.println(formObj.getAttachment());
return result;
}
Modal Class
public class ObservationModal implements Serializable {
int tooth;
private List<MultipartFile> attachment;
public int getTooth() {
return tooth;
}
public void setTooth(int tooth) {
this.tooth = tooth;
}
public List<MultipartFile> getAttachment() {
return attachment;
}
public void setAttachment(List<MultipartFile> attachment) {
this.attachment = attachment;
}
}
I can't get the values textbox values or attachment in controller. The ObservationModal is always null
To make the ajax call the url must be of the type '/projectName/actualurl'. In your case url:'/projectName/updateObservation'. And also add dataType:'text' to the call.
A file cannot be uploaded using AJAX. To make it happen
you can use formdata for fileupload but this work for only html5 supported browsers
var form = $('form')[0]; // You need to use standart javascript object here
var formData = new FormData(form);
And if you want it to work even for older browsers you can use iframe with form for fileupload.
For uploading a file normally you need to use encType="multipart/form-data" in your form.
If you want to use Ajax to upload a file, Along with Simple ajax call you need to use its fileupload plugin.
For more details have a look here: Link1, Link2, Link 3,
Link 4
I want to upload an excel file in my application using ajax,jQuery and Spring form. Following is my code. I am able to hit the controller with #modelAttribute which is nothing but a Simple Java Class having one Multipart file attribute but that file attribute in the FileUploadForm is null when the request is coming to Controller. Can anyone suggest what wrong I am doing. I am doing this in IE8 so can not use FormData. Thanks in advance.
JSP
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
var form = $('#myForm');
form.find('#submitButton').click(function() {
$.ajax({
type : "POST",
url : form.attr('action'),
enctype : 'multipart/form-data',
data : form.attr('modelAttribute'),
success : function(data) {
alert("Success"+data);
},
error : function(data) {
alert("error");
}
});
});
});
</script>
</head>
<body>
<form:form method="post" action="upload" id="myForm"
modelAttribute="uploadForm" enctype="multipart/form-data">
<table id="fileTable">
<tr>
<td><input name="file" id="uploadedFile" type="file" /></td>
</tr>
</table>
<br />
<!-- <button class="btn btn-primary" type="submit" value="Upload">
Upload</button> -->
<input type="submit" class="btn btn-primary" id="submitButton"
value="Upload" />
</form:form>
And following is my controller code.
Controller
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFileUpload(#ModelAttribute("uploadForm") FileUploadForm form,
Model model) {
MultipartFile file = form.getFile();
String name = file.getOriginalFilename();
FileSystemResource fsr = new FileSystemResource(name);
StatusVO statusVO = service.loadAndProcessUploadedFile(fsr.getFile());
model.addAttribute("status", statusVO);
return "/common/message";
}
Following is FileUplaodForm Class
FileUploadForm.java
import org.springframework.web.multipart.MultipartFile;
public class FileUploadForm {
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
If form is not getting submitted by submit button, simply try like this,
var form = $('#myForm');
form.find('#submitButton').click(function() {
form.submit(); //This will submit your form.
});
Hope this helps.
Hey Thanks all for your quick response but i got it solved. Ajax not at all works with file uploads. So I removed all ajax related code and made it simple form submit. Now working fine.