Adapting a jQuery function to send files - javascript

A function on our website fires for all of our forms. It uses jquery's serializearray method and works great.
I need to add a form with a file input, and serializearray doesn't handle files. I'm not new to Python and Django, but I am new to Jquery. And I'm having trouble adapting the function.
Since the formData class handles files, I thought I could change "data: serializedform" to "data: new formData(form)".
When I did that, Chrome's console displayed "Uncaught TypeError: Illegal invocation". Firefox's console displayed "Uncaught TypeError: 'append' called on an object that does not implement interface FormData."
Do I need to convert the FormData object to another type?
A snippet follows:
uploadfile.html:
function postAndLoad(form, url, panelDivID, btnName){
var serializedForm = $(form).serializeArray();
return request = $.ajax({
url: url,
dataType : 'html',
cache: 'false',
type : 'POST',
data: serializedForm, //data: new FormData(form) produces an error.
success: function (data) {
console.log("Completed POST");
error: function(data) {
console.log('There was a problem in postAndLoad()');
console.log(data);
}
});
return false;
};
…
<form enctype="multipart/form-data" onsubmit="postAndLoad(this, '{% url 'UploadFile' %}', 'panel_upload'); return false;" method='post'>
{% csrf_token %}
{{ form | crispy}}
<div class="row w-100">
<input class="btn" type='submit' name="form1btn" value="button" />
</div>
</form>
forms.py:
class UploadFile(forms.Form):
uploadFile = forms.FileField(label="Select file to upload")
sampleText = forms.CharField(label="Enter some text")

Related

Formdata is showing file but laravel's Request is showing null

I have a form in datatable as follows.
<form method="post" enctype="multipart/form-data">
<label for="file_'+row["course_id"]+'">
<i class="far fa-2x fa-file-pdf f-gray"></i>
</label>
<input type="file" id="file_'+row["course_id"]+'">
</form>
This shows a pdf button inside datatable for file upload. Onclick it will show a file browser for file selection.
Using javascript's FormData() I am passing the file to Laravel controller.
$(document).on("change", "[id^=file_]", function(e) {
var file_data = this.files[0];
var form_data = new FormData();
form_data.append("pdf_file", file_data);
$.ajax({
url: "/pdfUpload",
cache: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
$('div.flash-message').html(data).fadeOut(5000);
}
});
});
The request headers is as follows:
But the following code says there is no file and is returning null.
public function upload(\Google_Service_Drive $service, Request $request){
if ($request->hasFile('pdf_file')) {
dump('yes');
}else{
dump('no');
}
dd($request->pdf_file);
$data = file_get_contents(?)
}
Output:
Any help on what I'm missing here?
Also, I need to get $data = file_get_contents(?) working. What should I pass here

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();

form data upload multiple files through ajax together with text fields

Good day all,
I have a form wil multiple fields in it. Also, the form is being submitted through form data method using ajax to a php file.
The following is the javascript code submitting the form data.
$(".update").click(function(){
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
data.append('image',$('#picture').get(0).files[0]);
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
And, the following is the actual form:
<textarea name=body id=body class=texarea placeholder='type your message here'></textarea>
<input type=file name=image id=picture >
<input name=update value=Send type=submit class=update id=update />
This form and javascript work good as they are. However, I am trying to be able to upload multiple files to the php file using this one single type=file field attribute. As it is now, it can only take one file at a time. How do I adjust both the form and the javascript code to be able to handle multiple files uploads?
Any help would be greatly appreciated.
Thanks!
Here is ajax, html and php global you can access. Let me know if it works for you.
// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
// Full Ajax request
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
Updated HTML:
<form enctype="multipart/form-data" method="post">
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
Now, in PHP, you should be able to access your files:
// i.e.
$_FILES['file-0']
Here's another way.
Assuming your HTML is like this:
<form id="theform">
<textarea name="body" id="body" class="texarea" placeholder="type your message here"></textarea>
<!-- note the use of [] and multiple -->
<input type="file" name="image[]" id="picture" multiple>
<input name="update" value="Send" type="submit" class="update" id="update">
</form>
You could simply do
$("#theform").submit(function(e){
// prevent the form from submitting
e.preventDefault();
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
// pass the form in the FormData constructor to send all the data inside the form
data: new FormData(this),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
Because we used [], you would be accessing the files as an array in the PHP.
<?php
print_r($_POST);
print_r($_FILES['image']); // should be an array i.e. $_FILES['image'][0] is 1st image, $_FILES['image'][1] is the 2nd, etc
?>
More information:
FormData constructor
Multiple file input

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 :)

AJAX Post not sending form data

I have the following AJAX POST below, for some reason looking at my logging (server side) the request it's sending is is blank {} not JSON data is sent. I have exhausted all possible server side issues this is a client side issue with the script not sending data. why?
bootstrap-wizard.js found here -> GitHub
My page code overrides the script submit:
<script src="{{ STATIC_URL }}js/bootstrap-wizard.js"></script>
<script type="text/javascript">
$(function() {
var options = {width:1000};
var wizard = $("#some-wizard").wizard(options);
$("#open-wizard").click(function() {
wizard.show();
});
wizard.on("submit", function(wizard) {
$.ajax({
url: '/api/v1/rewards/campaigns/',
type: 'POST',
contentType: 'application/json; charset=UTF-8',
data: $('#wizard').serialize(),
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", $('input[name="csrfmiddlewaretoken"]').val());
},
success: function(data, textStatus) {
wizard.submitSuccess(); // displays the success card
wizard.hideButtons(); // hides the next and back buttons
wizard.updateProgressBar(0); // sets the progress meter to 0
console.log('success');
},
error: function(errorThrown){
// data = JSON.parse(errorThrown.responseText);
wizard.submitError(); // display the error card
wizard.hideButtons(); // hides the next and back buttons
console.log(errorThrown);
}
});
});
});
</script>
This is my form:
<form action="" method="post" class="form-horizontal" id="wizard" enctype="application/json" >
{% csrf_token %}
<div class="wizard" id="some-wizard">
<h1>{% trans "Setup Wizard" %}</h1>
<div class="wizard-card" data-cardname="card1">
<h3>{% trans "General" %}</h3>
etc, etc <=== all my form fields here
</div>
serialize() returns key/value formatted URL encoded data (x-www-form-urlencoded), not JSON. If your server side requires JSON then you need to change your data parameter:
$.ajax({
...
data : JSON.stringify({ input_a : 'value a', input_b : 'value b' }),
...
});
See this question for how to convert a form into JSON automatically.

Categories

Resources