jQuery Ajax File Upload
File upload is not possible through AJAX.
You can upload file, without refreshing page by using IFrame
.
You can check further details here.
UPDATE
With XHR2, File upload through AJAX is supported. E.g. through FormData
object, but unfortunately it is not supported by all/old browsers.
FormData
support starts from following desktop browsers versions.
- IE 10+
- Firefox 4.0+
- Chrome 7+
- Safari 5+
- Opera 12+
For more detail, see MDN link.
How to upload a file using Ajax on POST?
Looking back, the older answer is unpractical and not recommended. asnyc: false
pauses the entire Javascript to simply upload a file, you are likely firing other functions during the upload.
If you are using JQuery solely for the use of ajax
, then I recommand using axios
:
const axios = require('axios');
var formData = new FormData();
formData.append('imageFile', document.querySelector('#image_file').files[0]);
axios({
method: 'post',
url: 'your_url',
data: formData,
headers: {
"X-CSRFToken": CSRF_TOKEN, # django security
"content-type": "multipart/form-data"
}
}).then(function (response) {
# success
});
Axios Documentation
Jquery/Ajax answer:
var formData = new FormData();
formData.append('imageFile', $('#image_file')[0].files[0]);
formData.append('csrfmiddlewaretoken', CSRF_TOKEN); # django security
$.ajax({
url : 'your_url',
type : 'POST',
data : formData,
processData: false,
contentType: false,
success : function(data) {
# success
}
});
Jquery/Ajax Documentation
jQuery AJAX file upload PHP
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax
method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.
Your HTML is fine, but update your JS jQuery script to look like this:
(Look for comments after // <--
)
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
- Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
- Make sure it's writeable.
And a little bit about the PHP function move_uploaded_file
, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name']
is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize
AND post_max_size
configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
Upload file using ajax request
You can only upload files with AJAX but only in some modern browsers. I know it works in Firefox and Chrome (That's all I've tested so far).
Theres some good info here about it: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
As an alternative there's a great plugin for that sort of thing:
http://jquery.malsup.com/form/
This part may be of relevance to you:
http://jquery.malsup.com/form/#file-upload
It uses iframes to post to to upload in a background style of way.
Is it possible to use Ajax to do file upload?
No, it isn't possible to do this with javascript.
In order to give the 'AJAX' feel, however, you can submit a form to a hidden iframe and output the script results to it, then process from there. Google ajax iframe upload
and get started from there.
If you are using jQuery, there is also the Form plugin
which will automatically create this iframe for you if your form has any file fields in it. I haven't used it to do this, but I've heard good things.
As pointed out in the comments, you can also use something like the very popular SWFUpload
to accomplish the desired effect with Flash.
Uploading both data and files in one form using Ajax?
The problem I had was using the wrong jQuery identifier.
You can upload data and files with one form using ajax.
PHP + HTML
<?php
print_r($_POST);
print_r($_FILES);
?>
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
jQuery + Ajax
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
Short Version
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(data) {
alert(data);
});
});
Related Topics
How to Loop Through All Dom Elements on a Page
What Is This JavaScript Pattern Called and Why Is It Used
Selected Text Event Trigger in JavaScript
Does Never Resolved Promise Cause Memory Leak
Escaping Strings in JavaScript
Difference Between Using Bracket ('[]') and Dot ('.') Notation
How to Get the Selected Text in a Textarea
Tolocaledatestring() Changes in Ie11
React-Router: No Not Found Route
How to Use Z-Index in Svg Elements
How to Screenshot Website in JavaScript Client-Side/How Google Did It? (No Need to Access Hdd)