Ajax form submission with file upload not working Spring MVC - java

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

Related

Spring boot + Thymeleaf + ajax cannot send VO or DTO Controller

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/

Sending Cyrillic string from jsp to java class trough ajax with correct encoding

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.

Spring MVC - Trouble with AJAX form posting

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

How to prevent page refreshing? AJAX, Spring MVC

I have got a <form> and AJAX script that sending data from form to controller.
<form:form method="POST" modelAttribute="message"
accept-charset="utf-8" ng-app="vandh" ng-controller="validateCtrl"
name="messageForm" novalidation="true">
<form:textarea path="text" class="form-control" rows="1" name="message"
id="message" ng-model="message" required="true"></form:textarea>
<div style="color: black"
ng-show="messageForm.message.$dirty && messageForm.message.$invalid">
<span ng-show="messageForm.message.$error.required"><spring:message
code="label.entermessage" /></span>
</div>
<br>
<div class="text-center">
<button class="btn btn-success" id="addMessage" name="addMessage"><spring:message
code="label.sendmessage"/></button>
</div>
</form:form>
<script>
$("#addMessage").click(function() {
var text = $('#message').val();
$.ajax({
type : "POST",
url: "/app/user/messages/${iddialog}" ,
async : true,
dataType:'json',
contentType: 'application/json',
data : {
text : text
}
});
});
</script>
And here is my controller for this page
#RequestMapping(value = "/user/messages/{iddialog}", method = RequestMethod.POST)
public #ResponseBody Message messages(HttpServletRequest request, HttpServletResponse response,
#PathVariable(value = "iddialog") int iddialog, Principal principal,#RequestParam(value="text")String text ) {
System.out.println("ITS HERE");
if (checkingMessage(text) != true) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
Dialog dialog = new Dialog();
dialog.setIddialog(iddialog);
Message mess = new Message();
mess.setText(text);
mess.setDialog(dialog);
mess.setDate(dateFormat.format(date));
mess.setMessender(principal.getName());
this.messageService.addMessage(mess);
this.dialogService.updateUnreadMessInfo(iddialog, principal.getName());
System.out.println("message sent!");
return mess;
// return "redirect:/user/messages/"+iddialog;
}
else{
Message mess1 = new Message();
return mess1;
}
}
#RequestMapping(value = "/user/messages/{iddialog}", method = RequestMethod.GET)
public String messagesList(#PathVariable(value = "iddialog") int iddialog, Model model, Principal principal) {
model.addAttribute("message", new Message());
model.addAttribute("listMessagesForUser", messageService.listMessagesForUser(iddialog));
model.addAttribute("userDialogWith", dialogService.usernameDialogWith(iddialog, principal.getName()));
model.addAttribute("countOfNewUsers", this.usersService.countOfNewUsers());
model.addAttribute("allUserMess", this.dialogService.allNewMessForUser(principal.getName()));
System.out.println("ID dialog is: " + iddialog);
return "messagesWithUser";
}
When i'm sending data from AJAX script to my controller, it returns me my Message object:
But i need to prevent reloading my page when i'll submit my <form>. I saw a lot of guides but it's the highest result that i get! Help me pls! What i need to do that my page will not refresh when i'm submiting my form!!!!
You need to return false from your click handler to prevent the default action (submitting the form) from executing.
You can stop default action using prevent default.
https://api.jquery.com/event.preventdefault/
Based from your front end code you are using AngularJS, but you are using jQuery to trigger the button click.
What you can do is create a function in your controller(validateCtrl) to handle the click event and post the message model to the backend, by using the ng-click directive of angular and add an attribute type='button' to button to prevent triggering the submit of the form.
Your button would be like:
<button type="button" class="btn btn-success" id="addMessage" name="addMessage" ng-click="addMessageClick(message)">
Documentation on Angular $http: https://docs.angularjs.org/api/ng/service/$http
angular.module('app', []);
angular.module('app', []).controller('validateCtrl', ['$scope', '$http',
function($scope) {
//You could pass the message model here as a parameter or access it using $scope.message
$scope.addMessageClick = function(message) {
//Use AngularJS's $http or jQuery Ajax to post to backend and send the message model
console.log('test');
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<html>
<head></head>
<body ng-app="app">
<form name="messageForm" ng-controller="validateCtrl" novalidate>
<button ng-click="addMessageClick('test')">Test</button>
</form>
</body>
</html>
You have added the submit button with in the form, and when you click on the submit button along with ajax call because of the form the page is getting reloaded
Please put that submit button outside of the form tag and check, your page reloading problem will be resolved

File upload using ajax and jQuery in Spring without using FormData

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.

Categories

Resources