I'm trying to do a file upload with JSP / JQuery but I have to make a few Ajax calls before submission.
However, after the Ajax calls are made and the form is submitted the form fields are all empty on the server side?
If I don't call e.preventDefault() then it all works but I need to make Ajax calls pre-submission!
Thanks
CLIENT SIDE:
<form method="post" action="accept.htm" enctype="multipart/form-data">
...
<input type="file" name="thefile" id="thefile"/>
<input type="submit" name="uploadfile" id="uploadfile" value="Upload File"/>
...
</form>
$("form").on("submit", function(e)
{
e.preventDefault(); // stop the form being submitted for now
// make a few ajax calls
...
// submit the form in ajax success callback
$("form").unbind("submit");
$("form").submit();
}
SERVER SIDE:
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
ServletFileUpload servletFileUpload = new ServletFileUpload();
servletFileUpload.setFileSizeMax(Long.valueOf(maxUploadFileSize));
servletFileUpload.setProgressListener(new UploadProgressListener());
FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request);
if(isMultipart)
{
while(fileItemIterator.hasNext()) <--- empty?
{
...
}
}
try this
$("form").on("submit", function(e)
{
// make a few ajax calls
...
// finally submit
$("form").unbind("submit");
$("form").submit();
e.preventDefault(); // stop the form being submitted for now
}
e.preventDefault(); send return false may issue with ajax
Turns out I had a JQuery statement in one of the Ajax calls that disabled the file input field. When this was removed the file became available again on the server side. So disabling the file input field causes it to become unavailable for some reason.
Related
Im new to AJAX/JQuery, and I'm wondering if there is a way to send, via an AJAX request, data from an HTML form that includes a text file, and 2 separate text boxes. I have been able to send the data from the text boxes, but the file is not sent.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
// this is the id of the form
$("#SQLsubmit").submit(function() {
var url = "DAOserv"; // the script where you handle the form input.
$.ajax({
type : "POST",
url : url,
data : $("#SQLsubmit").serialize(), // serializes the form's elements.
success : function(data) {
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
This is my AJAX call^
<div class="row">
<form id="SQLsubmit" name="SQLsubmit">
<div class="form-group col-lg-4">
<textarea rows="11" id="BAU" name="BAU" class="form-control"
placeholder="BAU Reason" form="SQLsubmit"></textarea>
<input type="file" name="file" /> <input type="submit"
class="btn btn-primary" value="Submit">
</div>
<div class="form-group col-lg-8">
<textarea rows="11" id="SQL" name="SQL" class="form-control"
placeholder="SQL Statements" form="SQLsubmit"></textarea>
</div>
</form>
Here is the HTML.
If anyone could show me how to get the two text files, and the file into my Java Servlet (using the doPOST method), so I am able to parse all into strings, that would be greatly appreciated!
Thanks!
edit: The problem I am having when running the code in the original post is that the text fields get sent, but the file is not being sent.
You should define enctype: 'multipart/form-data. Otherwise how jquery should know you are sending a file.
This link might help:
How can I upload files asynchronously?
Have you tried
$("#SQLsubmit").submit(function() {
var url = "DAOserv"; // the script where you handle the form input.
$.ajax({
type : "POST",
url : url,
data : new FormData(this),
success : function(data) {
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
I have a web application with HTML and JQuery, in which it has a login form. When I click the submit button I am using ajax to send the data using Post request to a web service.
The web service is built with Java.
Here is my html form:
<form id="mdxLogin" action="" method="post">
<div class="ui-content">
<p><input type="email" id="mdxEmail" name="mdxEmail" class="ui-field-contain" value="" placeholder="MDX Email" /> </p>
<p><input type="password" id="mdxPassword" name="mdxPassword" class="ui-field-contain" value="" placeholder="MDX Password" /></p>
</div>
<div class="ui-content">
<input type="submit" class="ui-field-contain" value="Login" id="sub"/>
</div>
</form>
The below is my Ajax code to post to my web service
$("#mdxLogin").submit(function(e) {
e.preventDefault();
var mdxEmail = $("input[name=\"mdxEmail\"]").val();
var mdxPassword = $("input[name=\"mdxPassword\"]").val();
$.ajax({
type: "POST",
url:"http://localhost:8080/RestService/rest/loginService/login",
dataType:"json",
data: $("#mdxLogin").serialize(),
success: function(data, textStatus, jqXHR) {
// handle your successful response here
alert(data);
},
error: function(xhr, ajaxOptions, thrownError) {
// handle your fail response here
alert("Error");
}
});
})
And the below is the method in my web service
#POST
#Path("/login")
#Produces(MediaType.TEXT_PLAIN)
public String login(#FormParam("mdxEmail") String mdxEmail, #FormParam("mdxPassword") String mdxPassword) {
System.out.println(mdxEmail);
DBStudent s = new DBStudent();
String url = null;
if (s.checkLogin(mdxEmail, mdxPassword)) {
url = s.getCalendar(mdxEmail, mdxPassword);
}
return url;
}
So far what I managed to do is to post the data to my web service but didn't get any response. My question is how can I access the returned url from my web service with Ajax?
In your code I spot one error which should prevent it to work properly.
In the client side you're saying to jQuery that the expected type is JSON, but the server produces a string, in your case a URL, which is not JSON.
Therefore jQuery when tries to parse the data received fails because it's not JSON data. This mistake should trigger the jQuery error block.
Apply just this change in the client:
dataType:"text"
If you want to test your code without worrying about the Same Origin Policy you can disable it, look at these threads
Disable firefox same origin policy
Disable same origin policy in Chrome
I have a Following JSP:
<form action="UploadServlet" method="post" enctype="multipart/form-data">
Select file to upload: <input type="file" name="file" id =upfile"size="50" /> <input type="button" value="Save" onclick="javascript:uploadPartnerDetails();" class="buttons">
</form>
And DWR Script which calls remoted Java Method:
function uploadPartnerDetails() {
SMUDWR.uploadPartnerDetails(function(data) {
dwr.util.setValue("UserTypeDiv", data, {
escapeHtml: false
});
});
}
The Remoted Method uploadPartnerDetails()is:
try {
WebContext wctx = WebContextFactory.get();
HttpServletRequest request = wctx.getHttpServletRequest();
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(request)) {
// if not, we stop here
}
I get This Error :
the request doesn't contain a multipart/form-data or multipart/form-data stream, content type header is text/plain
The Problem is the request above does not contain multipart/form-data.
How to I get that from this request?
In general DWR calls are AJAX calls and in AJAX we cannot upload files just like form data.
There are different ways to upload files using AJAX calls
Find different ways provided in answers to this question jQuery Ajax File Upload
Go through these and you will get better understanding of file handling with AJAX
I am new to JQuery, I am running into a wierd issue here, I try to do a post of my HTML form to a servlet, and try to print data on the servlet. Data gets printed most of the times I submit the form (say 7 times out of 10) with new values. But It fails the other 3 times, I could not find a pattern at which this is failing.
I tried using firebug and chrome tool, I don't see an error on the console, and I get 200 response in the resources/HTML tool in chrome every time I submit the form with correct values set.
Here is my code
HTML
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.16.custom/js/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<form id="fcall">
<p> Start Date: <input type="text" name="start" id="ibox_start">
End Date: <input type="text" name="end" id="ibox_end"> </p>
<div id="buttonID">
<input type="submit" value=" Find " class="button"></div>
</form>
main.js
$().ready(
function(){
$('#ibox_start').datepicker();
$('#ibox_end').datepicker();
$('#fcall').submit(
function(){
var start = $('#ibox_start').val();
var end = $('#ibox_end').val();
alert(start);
$.post("DServlet", {start:start,end:end}, function(data) {});
}
);
}
);
Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String start = request.getParameter("start");
String end = request.getParameter("end");
System.out.println("Date Recieved "+start);
}
I would expect to see one of the following :
natural HTML form submission
natural HTML form submission with a submit handler which validates form values and returns either true to allow form submission or false to suppress it.
a submit handler that submits form data by AJAX, establishes a .done() handler to handle the HTTP response, and returns false to inhibit natural HTML form submission.
The code above looks like a hybrid of these possibilities.
for me it seems impossible but expecting clarification on it. i am sending a request as follow :
<form action="/name" method="get">
<input type="text" />
<input type="submit" />
</form>
Now action class at server side manipulates & send the response to client, can i handle this response by ajax somehow ??
Yes, but you have to submit it via ajax (XmlHttpRequest) in order to be able to get the response that way.
Using jQuery makes this simple:
$.post("/name", {param:param}, function(data) {
});
In that example you should pass manually each form field as param. In case of bigger forms this is not that good. So you can use serialize():
$.post($("#yourForm").attr("action"),
$("#yourForm").serialize(),
responseHandlerFunction);