Unable to fetch Input File in servlet from request object - javascript

I have a requirement to fetch the uploaded input file from form and save it into mysql database. Here I am unable to fetch the input file from request object.
My servlet:
#Component(service = Servlet.class, property = {
"service.description=" + "************** Servlet",
"sling.servlet.methods=" + HttpConstants.METHOD_POST,
"sling.servlet.paths=" + "/bin/uploadtestservlet" })
public class UploadTestServlet extends SlingAllMethodsServlet{
#Reference
UploadAdmissionFormService uploadService;
private static final long serialVersionUID = 1L;
private final Logger LOGGER = LoggerFactory
.getLogger(UploadTestServlet .class);
protected void doPost(SlingHttpServletRequest request,
SlingHttpServletResponse response) {
try{
if(ServletFileUpload.isMultipartContent(request)){
List<File> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(File item : multiparts){
LOGGER.info("Name :::"+new File(item.getName()).getName()); //
}
}catch(Exception e){
}
}
My js:
$("#uploadSubmit").click(function(e) {
$.ajax({
type: "POST",
url: "/bin/uploadAdmissionForm",
data: 'passport=' +$('#uploadPhoto').get(0).files.item(0),
success: function(msg) {
},
});
});
HTML:
<form method="POST" enctype="multipart/form-data" id="upload-details-form">
<input type="file" name="uploadPhoto" id="uploadPhoto" class="uploadPhoto">
<div class="upload-photo">
<div class="upload-photo-content">
<h4>UPLOAD PHOTO</h4>
<p>Upload your recent passport size (3.5 x 4.5cm) color photograph (format should be jpg, gif, png, jpeg, bmp and maximum file size alloted is 1 MB)</p>
</div></div><form>
Exception:
Exception occurred in doPost :the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded; charset=UTF-8
Even though I have added enctype="multipart/form-data" at form level, this error is getting throw. Can someone please help me here. Thanks

Your ajax does not specify a file. You have to add processData:false,contentType:false to your method.
$("#uploadSubmit").click(function(e) {
$.ajax({
type: "POST",
url: "/bin/uploadAdmissionForm",
data: new FormData( this ), //this is needed
processData: false, //this is needed
success: function(data) {
//handle return here
},
contentType: false //this is needed
});
});
Here are some links about it:
jQuery AJAX file upload PHP
upload file through ajax
How to upload a file using jQuery.ajax and FormData

Related

Submit a Form using AJAX in ASP.Net Core MVC

I am working with ASP.Net Core 2.1, and trying to upload a file while returning it's url, without refreshing the page.
I am trying to write the JavaScript in site.js as the _RenderPartial("scripts") renders all scripts at the end of the page and hence directly using script tag in the razor view is not working. Secondly, adding it to site.js gives me an opportunity to call the script across the site views.
My Controller action looks like :
[HttpPost]
[DisableRequestSizeLimit]
public async Task<IActionResult> Upload()
{
// Read & copy to stream the content of MultiPart-Form
// Return the URL of the uploaded file
return Content(FileName);
}
My view looks like :
<form id="FileUploadForm" action="~/Resources/Upload" method="post" enctype="multipart/form-data">
<input name="uploadfile" type="file" />
<button name="uploadbtn" type="submit" onclick="SubmitForm(this.parentElement, event)">Upload</button>
The site.js currently looks like :
function SubmitForm(form, caller) {
caller.preventDefault();
$.ajax(
{
type: form.method,
url: form.action,
data: form.serialize(),
success: function (data) { alert(data); },
error: function (data) { alert(data); }
})}
Presently, the code bypasses the entire script and the file is uploaded and new view displaying the file name is returned. I need help to create the javascript.
Unfortunately the jQuery serialize() method will not include input file elements. So the file user selected is not going to be included in the serialized value (which is basically a string).
What you may do is, create a FormData object, append the file(s) to that. When making the
ajax call, you need to specify processData and contentType property values to false
<form id="FileUploadForm" asp-action="Upload" asp-controller="Home"
method="post" enctype="multipart/form-data">
<input id="uploadfile" type="file" />
<button name="uploadbtn" type="submit">Upload</button>
</form>
and here in the unobutrusive way to handle the form submit event where we will stop the regular behavior and do an ajax submit instead.
$(function () {
$("#FileUploadForm").submit(function (e) {
e.preventDefault();
console.log('Doing ajax submit');
var formAction = $(this).attr("action");
var fdata = new FormData();
var fileInput = $('#uploadfile')[0];
var file = fileInput.files[0];
fdata.append("file", file);
$.ajax({
type: 'post',
url: formAction,
data: fdata,
processData: false,
contentType: false
}).done(function (result) {
// do something with the result now
console.log(result);
if (result.status === "success") {
alert(result.url);
} else {
alert(result.message);
}
});
});
})
Assuming your server side method has a parameter of with name same as the one we used when we created the FormData object entry(file). Here is a sample where it will upload the image to the uploads directory inside wwwwroot.
The action method returns a JSON object with a status and url/message property and you can use that in the success/done handler of the ajax call to whatever you want to do.
public class HomeController : Controller
{
private readonly IHostingEnvironment hostingEnvironment;
public HomeController(IHostingEnvironment environment)
{
_context = context;
hostingEnvironment = environment;
}
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
try
{
var uniqueFileName = GetUniqueFileName(file.FileName);
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads, uniqueFileName);
file.CopyTo(new FileStream(filePath, FileMode.Create));
var url = Url.Content("~/uploads/" + uniqueFileName);
return Json(new { status = "success", url = url });
}
catch(Exception ex)
{
// to do : log error
return Json(new { status = "error", message = ex.Message });
}
}
private string GetUniqueFileName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_"
+ Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
}
Sharing the code that worked for me, implementing #Shyju's answer.
View ( Razor Page ):
<form name="UploadForm" action="~/Resources/Upload" method="post" enctype="multipart/form-data">
<input name="uploadfile" type="file" />
<button name="uploadbtn" type="submit" onclick="SubmitForm(this.parentElement, event)">Upload</button>
AJAX code added in Site.js (to make it a reusable):
// The function takes Form and the event object as parameter
function SubmitForm(frm, caller) {
caller.preventDefault();
var fdata = new FormData();
var file = $(frm).find('input:file[name="uploadfile"]')[0].files[0];
fdata.append("file", file);
$.ajax(
{
type: frm.method,
url: frm.action,
data: fdata,
processData: false,
contentType: false,
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
})
};
if you want to submit the form without using ajax request
var form = document.getElementById('formId');
form.submit();

Sending a File (PDF) through ajax to a JSP Servlet

I am trying to send two PDF Files )initially just one) through an HTML form using javascript (jquery or not), I have to receive both files in a controller of a JSP page (using Spring) and do something with both files.
Right now I have been trying some of the answers already posted here in SO, but I am not being able to get it to work correctly.
My HTML File
<form id="searchForm">
<table class=rightAlignColumns>
<tr>
<td><label for="File1"><spring:message code='File1' />:</label></td>
<td><input id="File1" type="file" name="File1" /> </td>
<td><label for="file2"><spring:message code='File2' />:</label></td>
<td><input id="file2" type="file" name="file2" /> </td>
</tr>
</table>
<br/>
<input type="submit" value="<spring:message code='Btn' />" />
</form>
My javascript
var fd = new FormData();
alert(document.getElementById('File1').files.length);
fd.append( 'File1', document.getElementById('File1').files[0] );
// fd.append( 'File2', document.getElementById('File2').files[0]);
$.ajax({
url:'myurl.json',
data: fd,
cache:false,
processData:false,
contentType:false,
type: 'POST',
success: function(data){
// alert(data);
}
});
On the controller I am doing what this other post said.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldName = item.getFieldName();
String fieldValue = item.getString();
// ... (do your job here)
} else {
// Process form file field (input type="file").
String fieldName = item.getFieldName();
String fileName = FilenameUtils.getName(item.getName());
InputStream fileContent = item.getInputStream();
// ... (do your job here)
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
// ...
}
The problem I think it is in the javascript, because when the code enters to the Controller the list "items" has a size of 0, and going into the exception.
The expected result would be the user loading a PDF file into the Form, hitting submit and ajax sending the file to the server (controller), doing stuff correctly and sending back a result.
Right now the client is not uploading correctly the file.
As a side note, the file I am uploading is going to be used by pdfbox or google ocr in the controller.
Thanks in advance!
It worked using the next code:
JS:
function doAjax() {
// Get form
var form = $('#id_form')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "controller/myMethod",
data: data,
processData: false, //prevent jQuery from automatically transforming the data into a query string
contentType: false,
cache: false,
dataType:'json',
success: function (e) {
$("#result").text(data);
alert("Success");
},
error: function (e) {
$("#result").text(e.responseText);
alert("Error");
},
complete: function () {
// Handle the complete event
alert("Complete");
}
});
}
And on the controller
#RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
public String uploadFileMulti(#RequestParam("file") MultipartFile file,HttpServletRequest request) {
try {
//storageService.store(file, request);
System.out.println(file.getOriginalFilename());
return "You successfully uploaded " + file.getOriginalFilename();
} catch (Exception e) {
return "FAIL!";
}
}
My HTML file
<form class="form-horizontal" method="POST" enctype="multipart/form-data" id="id_form">
<label for="file">File:</label>
<input id="file" type="file" name="file" />
</form>

Trying to POST multipart/form-data by javascript to web api

Here i have a form in which i have a input type file to upload my file when the upload button is click i need to post the multipart/form-data to web api
where i upload the file to Minio Server.I have pasted the javascript and web api i use below.
When i press upload button after i get 500 (Internal Server Error).Help me with suggestions.
$("#upload").click(function () {
var file = new FormData($('#uploadform')[0]);
file.append('tax_file', $('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: 'http://localhost:53094/api/values',
data: file,
//use contentType, processData for sure.
contentType: "multipart/form-data",
processData: false,
beforeSend: function () {},
success: function (msg) {
$(".modal .ajax_data").html("<pre>" + msg +
"</pre>");
$('#close').hide();
},
error: function () {
$(".modal .ajax_data").html(
"<pre>Sorry! Couldn't process your request.</pre>"
);
$('#done').hide();
}
});
});
[HttpPost]
public string Post(IFormFile file)
{
try
{
var stream = file.OpenReadStream();
var name = file.FileName;
minio.PutObjectAsync("student-maarklist", "sample.jpeg", stream, file.Length);
return "Success";
}
catch (Exception ex)
{
return ex.Message;
}
}
I think you need not mention localhost just the path to the file will do. or replace it with IP of the localhost.
Sorry i have dont a mistake the name i appended in javascript is not save as the name i gave in web api.
I changed,
file.append('tax_file', $('input[type=file]')[0].files[0]);
To
file.append('file', $('input[type=file]')[0].files[0]);
and it worked .

How to reload a specfic part of a JSP with a new Model over AJAX (Spring MVC)?

What am I using?
Tomcat 7.0.56
JAVA 1.8
Spring MVC
jQuery
What is the goal?
I'm implementing a content directory.
The user searches for a specific name or phone number for example. Then a list of contacts shows up on the left side of the page. On the right side there should details be displayed of a contact that gets selected.
Where is the problem?
My problem lays on the part of showing the details.
My Code:
index.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html >
<%# include file="includes/header.jsp" %>
<body>
<div class="pageContainer container-fluid">
<div class="row">
<%# include file="searchBar.jsp" %>
</div>
<div class="row">
<div class="containerOverView col-lg-5 col-md-6 col-sm-12 col-xs-12">
<%# include file="overView.jsp" %>
</div>
<div class="containerDetailView col-lg-7 col-md-6 col-sm-12 col-xs-12">
<%# include file="detailView.jsp" %>
</div>
</div>
</div>
</body>
</html>
detailView.jsp
<ul class="flex-container">
<li class="flex-item-photo">Photo</li>
<li class="flex-item-pdetails">Personal Details</li>
<li class="flex-item-cdetails">Company Details</li>
<li class="flex-item-map">Map:
${detailSearchResult.name}
</li>
</ul>
MainController.java
// Delivers the refresh-information for the ajax request, when the detail view gets reloaded
#RequestMapping(value = "/refreshDetail", method = RequestMethod.POST)
#ResponseBody
private String refreshDetailView(HttpServletRequest hsr, #RequestParam String id, ModelMap model){
model.addAttribute("detailSearchResult", Dao.getDetailViewData(id));
return "detailView";
}
main.js
$(document).ready(function(){
$(".overViewListEmployee").click(function () {
var id = $(this).find(".overViewEmployeeID").text();
console.log("Works: " + id + ".");
$.ajax({
type: "POST",
accepts: "text/plain",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "/refreshDetail",
data: ({"id" : id}),
success: function(response) {
$(".containerDetailView").html(response);
}
});
});
});
What exactly doesn't work?
It seems to me, that the ajax request doesn't really get a valid response. From my understanding ajax accepts every kind of response but somehow, when I debug the JavaScript it says that the response has a Response Error: response is not defined
Error Codes:
With the code above:
400: Failed to load resource: the server responded with a status of 400 (Bad Request)
When I comment out following line in main.js:
//contentType: "application/json; charset=utf-8",
406: (Not acceptable)
What does work? (due to debugging)
When I debugged the code I saw that the value of the id is getting into the Controller correctly and also the function Dao.getDetailView(id) works properly. So it's really just an issue of the response.
What else have I tried?
I'm not sure if it works that way, by returning a string with the name of the detailView.jsp page that should be reloaded since I don't know if the model I'm adding the attribute to is also going with it and rendered in the index.jsp (where detailView.jsp is included).
So I also tried to put the Controller-Function like this:
// Delivers the refresh-information for the ajax request, when the detail view gets reloaded
#RequestMapping(value = "/refreshDetail", method = RequestMethod.POST)
private ModelAndView refreshDetailView(#RequestParam String id, ModelMap model){
model.addAttribute("detailSearchResult", Dao.getDetailViewData(id));
return new ModelAndView("detailView");
}
and removing this line from main.js:
accepts: "text/plain",
I also tried by returning the model as well:
return new ModelAndView("detailView", model);
I'm not working with JavaScript that often, so it's possibly a really silly and obvious mistake but I can't seem to find it. I literally tried out everything I could find but it looks like I'm stuck here.
I would really appreciate any kind of help on this case :)
Update:
main.js
$(".overViewListEmployee").click(function () {
var id = parseInt($(this).find(".overViewEmployeeID").text());
console.log("Works: " + id + ".");
$.ajax({
type: "POST",
accept:"text/html",
//contentType: "application/json; charset=utf-8",
dataType: "html",
url: "/refreshDetail",
data: ({"id": id}),
success: function(response) {
$(".containerDetailView").html(response);
}
});
});
MainController.java
// Delivers the refresh-information for the ajax request, when the detail view gets reloaded
#RequestMapping(value = "/refreshDetail", method = RequestMethod.POST, produces = MediaType.TEXT_HTML_VALUE)
#ResponseBody
private ModelAndView refreshDetailView(HttpServletRequest hsr, #RequestBody IdObject id, ModelMap model){
model.addAttribute("detailSearchResult", Dao.getDetailViewData(id.getId()));
return new ModelAndView("detailView", model);
}
IdObject.java
public class IdObject {
int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Right now the Controller isn't reached at all - still got that 415 Error.
Update 2:
WebInit.java (before)
#Configuration
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer{
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
WebInit.java (after)
#Configuration
public class WebInit implements WebApplicationInitializer{
#Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext =
new AnnotationConfigWebApplicationContext();
rootContext.register(WebConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext =
new AnnotationConfigWebApplicationContext();
dispatcherContext.register(RootConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
Now I'm not sure if it's what you meant but from what I read #AnnotationDrivenConfig is the same as to do it with AnnotationConfigWebApplicationContext. And since I'm doing it with pure Java based Configuration I figured, that'd be my way to go.
But I still got the same error though.
WebConfig.java
#Configuration
#EnableWebMvc
#ComponentScan("com.avectris.newtel")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/view/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/sass_compiled/**").addResourceLocations("/sass_compiled/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
converter.setObjectMapper(objectMapper);
converters.add(converter);
super.extendMessageConverters(converters);
}
}
Taking a look to your ajax request I think you are trying to send a json object (but you are not, really) and then your are trying to get the value for the id with #RequestParam instead of #RequestBody.
If you do not want to send a json object in the ajax payload, then your content-type is wrong. Try something like this. The data property is going to be is converted to a query string by jQuery.
$(document).ready(function(){
$(".overViewListEmployee").click(function () {
var id = $(this).find(".overViewEmployeeID").text();
console.log("Works: " + id + ".");
$.ajax({
type: "POST",
headers: {
"Accept" : "text/html",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
},
url: "/refreshDetail",
//you can get rid of data if you change your url to "/refreshDatil?id="+id
data: {"id" : id},
success: function(response) {
$(".containerDetailView").html(response);
}
});
});
});
If you really want to send a json object, as I have already said on my comments, you need do some changes at your controller level.
Edit
Ok, you are now mixing the two possible solutions. With your current ajax object you are not sending a json object, but a normal http request. You can check the network tab at your browser when the ajax request happend and you will see a request like /refreshDetail?id=yourid, without json object in the paylod.
Your controller, on the other hand, using #RequestBody is trying to get an object like IdObject from the payload, but your are not doing a request like that. Your controller should looks like:
#RequestMapping(value = "/refreshDetail", method = RequestMethod.POST, produces = MediaType.TEXT_HTML_VALUE)
private ModelAndView refreshDetailView(HttpServletRequest hsr, #RequestParam int id, ModelMap model){
model.addAttribute("detailSearchResult", Dao.getDetailViewData(id));
return new ModelAndView("detailView", model);
}
Also remove the brackets from the data property at your ajax object:
$(".overViewListEmployee").click(function () {
var id = parseInt($(this).find(".overViewEmployeeID").text());
console.log("Works: " + id + ".");
$.ajax({
type: "POST",
accept:"text/html",
//contentType: "application/json; charset=utf-8",
dataType: "html",
url: "/refreshDetail",
data: {"id": id},
success: function(response) {
$(".containerDetailView").html(response);
}
});
});
In case you want to send a json payload
If what you really need is send a json object from javascript then you need to change your ajax request
$(".overViewListEmployee").click(function () {
var id = parseInt($(this).find(".overViewEmployeeID").text());
console.log("Works: " + id + ".");
$.ajax({
type: "POST",
accept:"text/html",
dataType: "html",
contentType: "application/json",
url: "/refreshDetail",
data: JSON.stringify({"id": id}),
success: function(response) {
$(".containerDetailView").html(response);
}
});
});
With contentType jQuery is setting the header Content-Type, telling your controller the request is coming with a json payload. Then, JSON.stringify is converting the javascript object with the info to be send into a json string and it will be used by jQuery as payload.
On the backend side, your controller, now, should use #RequestBody because the info is not coming within the request parameters, but a json payload. So, it should looks like something to this:
#RequestMapping(value = "/refreshDetail", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.TEXT_HTML_VALUE)
private ModelAndView refreshDetailView(HttpServletRequest hsr, #RequestBody IdObject id, ModelMap model){
model.addAttribute("detailSearchResult", Dao.getDetailViewData(id.getId()));
return new ModelAndView("detailView", model);
}
The consumes property at the request mapping, in this case, is not mandatory, as you do not have any other mapping to the same value /refreshDetail, but it makes the code easier to read.
You do not have to use #ResponseBody at your controller, on any of this cases, because you are sending back a view. You will use it when sending back a json, xml, etc.

Django + Ajax | File Upload | Server doesn't recognise Ajax Request

I am trying to implement file upload using ajax with Django but facing some problem.
When the user tries to upload the files after selecting the file and submitting the form, then as per my understanding , an ajax request should be send to the server using POST method ,but in my case a POST request is being made to the server, but the server is not able to identify it as an ajax request and browser is redirected to http://<server>:<port>/upload/ and the contents on this page are as follows.
{"status": "error", "result": "Something went wrong.Try Again !!"}
Django Version: 1.6.2
Python Version: 2.7.5
Also, testing on Django Development Server.
views.py
def upload(request):
logging.info('Inside upload view')
response_data = {}
if request.is_ajax():
logging.info('Is_AJAX() returned True')
form = UploaderForm(request.POST, request.FILES)
if form.is_valid():
logging.info('Uploaded Data Validated')
upload = Upload( upload=request.FILES['upload'] )
upload.name = request.FILES['upload'].name
upload.save()
logging.info('Uploaded Data Saved in Database and link is %s' % upload.upload)
response_data['status'] = "success"
response_data['result'] = "Your file has been uploaded !!"
response_data['fileLink'] = "/%s" % upload.upload
return HttpResponse(json.dumps(response_data), content_type="application/json")
response_data['status'] = "error"
response_data['result'] = "Something went wrong.Try Again !!"
return HttpResponse(json.dumps(response_data), content_type='application/json')
Template
<form id="uploadForm" action="/upload/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="fileInput" class="input-file" name="upload" type="file">
<input type="submit" value="Post Images/Files" />
</form>
Javascript 1:
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Javascript 2
var options = {
url: '/upload/',
type: "POST",
error: function(response) {
alert('Something went Wrong. Try Again');
},
success: function(response) {
if ( response.status == 'success' ) {
alert('success');
}
}
};
$('#uploadForm').ajaxSubmit(options);
Question:
1) Why is Django not able to recognize the ajax request and value of request.is_ajax() is always False.
2) Even if the server doesn't recognize ajax request why is my browser getting redirected to another page ?
There is another similar question here but with no result.
This works for me. You need a jquery.form.js
$("#uploadForm").submit(function(event) {
$(this).ajaxSubmit({
url:'{% url upload_file %}',
type: 'post',
success: function(data) {
console.log(data)
},
error: function(jqXHR, exception) {
console.log("An error occurred while uploading your file!");
}
});
return false;
});
Here's the similar question here with answers.
Make sure that javascript code block
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
loaded after your uploadForm html form in DOM on page. In your case seems you trying to bind submit handler with form element which not yet loaded so when you click, it send simple POST request.
1) why is_ajax() not working?
Have you included the JQuery form plugin (jquery.form.js) ? ajaxSubmit() needs that plugin.
Take a look at http://jquery.malsup.com/form/
If it's already done, you might take a look at the HTTPRequest object
Django Documentation says HttpRequest.is_ajax()
Returns True if the request was made via an XMLHttpRequest. And if you are using some javascript libraries to make the ajax request, you dont have to bother about this matter. Still you can verify "HTTP_X_REQUESTED_WITH" header to see if Django received an XMLHttpRequest or not.
2) Why page redirects?
As I said above, JQuery form plugin is needed for handling the ajax request and its call back. Also, for ajaxSubmit() you need to override the $(#uploadForm).submit()
$('#uploadForm').submit( function (){
$(this).ajaxSubmit(options);
return false;
});
Hope this was helpful :)

Categories

Resources