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
Related
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.
I'm really getting started with controllers for my small application, and i have this for now:
#RequestMapping("/users/{id}")
public ModelAndView showMemeber(#PathVariable Integer id) {
ModelAndView mav = new ModelAndView("user/show");
mav.addObject("title", "Show User");
mav.addObject("user", userService.findById(id));
return mav;
}
#RequestMapping(value="/users/{id}", method=RequestMethod.DELETE)
public String deleteMemeber(#PathVariable Integer id) {
userService.delete(id);
return "redirect:users";
}
the first one, is working properly, but the second doesn't, i have the following view for the first controller:
<div class="panel-heading">Personal information</div>
<div class="panel-body">
<form>
...
<button type="submit" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete {{ user.username }}?')"><span class="glyphicon glyphicon-remove"></span> Delete</button>
</form>
</div>
like you see, i have two buttons here, one for edit the object and one for delete it.
Once deleted it, must redirect to https://<my domain>/users.
The problem is, when i click on Delete it just refresh the page and the object persist on the database, what is wrong here?
I try send a DELETE request like curl -X "DELETE" http://localhost:8080/my-app/users/18 but this didn't work.
I try another alternative using jQuery's ajax-method (but the same error persist):
$.ajax({
url: '/users/' + someUserId,
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
You have to use ajax to send a DELETE from the web page. The form tag itself only supports POST or GET. In your submit-Handler you have to suppress the default behaviour of the submit button, i.e. the submit of the form via GET or POST (event.preventDefault()):
$("form").submit(function (event) {
event.preventDefault();
$.ajax({
url: '/users/' + someUserId,
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
}
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.