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.
Related
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 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
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
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
hi I am trying to Use Ajax with Spring Mvc Porltet In liferay.I Have a Jsp File and Controller Class.I want to insert a data in the form but my controller class is Not Called.So please Help Me to Solve this Problem.When I Click on submit My COntroller class is not called.
my .jsp code as follws:
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects/>
<portlet:renderURL var="renderOneMethodURL">
<portlet:param name="action" value="renderOne"></portlet:param>
</portlet:renderURL>
<portlet:actionURL var="actionOneMethodURL">
<portlet:param name="action" value="actionOne"></portlet:param>
</portlet:actionURL>
Call RenderOne method
<%-- <form action="${actionOneMethodURL}" method="post">
User Name: <input type="text" name="userName">
<input type="submit">
</form> --%>
<div id="request">
<div id="bigForm">
<h2> REQUEST</h2>
<h3> Enter Request Details :</h3>
<p>Name: <input name="name">
Code: <input name="code" size="6">
Request: <input name="request">
Type: <input name="type" size="6"></p>
<hr></hr>
<div class="block2">
<h2> Attribute Value Pair(Avp)</h2>
<p class="remark"> Recursive structure of avp. You can nest one AVP inside another..</p>
<div data-holder-for="branch"></div>
</div>
<div class="clear"></div>
<p> </p>
<p class="remark" align="right" padding-right:"1cm";>Click here to generate JSON representation of the form</p>
<p align="right">
<input type="submit" id="saveBigForm"></p>
</div>
<style type="text/css">a {text-decoration: none}</style>
<!-- Subforms library -->
<div style="display:none">
<div data-name="branch">
<table>
<td>Name:</td> <td><input name="name"></td>
<td>Code:</td> <td><input name="code"></td>
<td>Vendor:</td> <td><input name="vendor"></td>
<td>Multiplicity:</td><td><input name="multiplicity"></td>
<td>Index:</td><td><input name="index"></td>
<td>CDR-Index:</td><td><input name="cdrIndex"></td>
<tr>
<td >Type:</td><td><input name="type"></td>
<td>Value:</td><td><input name="value"></td>
</tr>
</table>
<div style="margin:10px; border-left:3px solid black" data-holder-for="branch"></div>
</div>
</div>
<div id="popup"></div>
</div>
and my javascript
$('#saveBigForm').click(function(){
var json = $('#bigForm').jqDynaForm('get');
showFormJson(json);
// var myInfoUrl = "<c:out value="${actionOneMethodURL}" />";
$.ajax({
type: "POST",
//url: "http://localhost:9090/first-spring-mvc-portlet//WEB-INF/servlet/view",
//url : myInfoUrl,
url : "${actionOneMethodURL}",
data: JSON.stringify(json),
dataType: "json",
success: function(response){
// we have the response
if(response.status == "SUCCESS"){
$('#info').html("Success........!Request has been added......... ");
}else{
$('#info').html("Sorry, there is some thing wrong with the data provided.");
}
},
error: function(e){
alert('Error: ' + e);
}
});
});
and controller class as follows
package com.myowncompany.test.springmvc.controller;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ParamUtil;
#Controller(value = "MyFirstSpringMVCTestController")
#RequestMapping("VIEW")
public class MyFirstSpringMVCTestController {
private static Log log = LogFactoryUtil.getLog(MyFirstSpringMVCTestController.class);
/*
* maps the incoming portlet request to this method
* Since no request parameters are specified, therefore the default
* render method will always be this method
*/
#RenderMapping
public String handleRenderRequest(RenderRequest request,RenderResponse response,Model model){
return "defaultRender";
}
#RenderMapping(params = "action=renderOne")
public String openSaveSearchPopup(RenderRequest request, RenderResponse response, Model model){
return "render1";
}
#RenderMapping(params = "action=renderTwo")
public String openDeeplinkForInfoI(RenderRequest request, RenderResponse response){
return "render2";
}
#RenderMapping(params = "action=renderAfterAction")
public String testRenderMethod(RenderRequest request, RenderResponse response){
log.info("In renderAfterAction method");
return "renderAfterAction";
}
#ActionMapping(params = "action=actionOne")
public void actionOne(ActionRequest request, ActionResponse response) throws IOException {
String userName=ParamUtil.get(request, "userName", "");
log.info("server input stream is :::"+ request.getPortletInputStream().toString());
System.out.println("we ri nnnnnnnnn");
log.info("userName is==>"+userName);
response.setRenderParameter("action", "renderAfterAction");
}
#ActionMapping(params = "action=actionTwo")
public String addMyChannelAction(ActionRequest actionRequest, ActionResponse actionResponse) {
return "action2";
}
}
iam getting the log as follows:
09:36:56,291 INFO [DispatcherPortlet:119] Portlet 'firstspringmvc' configured successfully
09:36:56,300 INFO [localhost-startStop-19][PortletHotDeployListener:454] 1 portlet for first-spring-mvc-portlet is available for use
10:09:49,460 WARN [http-bio-9090-exec-138][404_jsp:121] {msg="/$%7BactionOneMethodURL%7D", uri=/$%7BactionOneMethodURL%7D}
10:09:54,325 WARN [http-bio-9090-exec-139][404_jsp:121] {msg="/$%7BactionOneMethodURL%7D", uri=/$%7BactionOneMethodURL%7D}
Try with jsp core tag,
url : "<c:url value='/VIEW/actionOne' />"
OR
url : "<c:out value='${actionOneMethodURL}' />"
Include JSTL core in JSP i.e.:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
and Change your ajax URL
url : "${actionOneMethodURL}"
to
url : "<c:url value='/VIEW/actionOne' />",
From what you have told us so far I can identify those causes:
your javascript has a problem and is not running at all (open with google chrome or firefox and press F12. Go to the Console tab and tell us if you have any errors there.
since you have a different javascript file, as the warning said, ${actionOneMethodURL}is not defined there. So you can do it like this:
In your HTML (the .jsp file you postet at top):
<script type="text/javascript">
ajaxLink = "${actionOneMethodURL}";
</script>
In your javascript file:
url : window.ajaxLink;
Experiment with this, I have no way to test it may need some tweaks like where you add the script (near the beginning of the document, near the end), and if the " surrounding the ${actionOneMethodURL} are needed.
in .jsp page add
var actionurl =${actionOneMethodURL};
in example.js on ajax call
$.ajax({
type: "POST",
url : actionurl,
data: JSON.stringify(json),
dataType: "json",
success: function(response){
// we have the response
if(response.status == "SUCCESS"){
$('#info').html("Success........!Request has been added......... ");
}else{
$('#info').html("Sorry, there is some thing wrong with the data provided.");
}
},
error: function(e){
alert('Error: ' + e);
}
});