I have a file uploading system using jquery's formdata
the thing goes like this --->
HTML
<form id="upload-form" method="post" enctype="multipart/form-data" action="resource/php/upload.php">
<input style="display:none;" type="file" id="upload" multiple>
</form>
JQUERY
$('#upload').change(function(e){
var formdata = new FormData(),file;
$('#ajax-loader').show(); //simple gif loader
for(var i=0;i<this.files.length;i++){
file = this.files[i];
var ftype = file.type;
formdata.append("files[]", file);
}
if (formdata) {
$.ajax({
url: "resource/php/upload.php",
type: "POST",
data: formdata,
dataType : 'json',
processData: false,
contentType: false,
success: function(data) {
$('#ajax-loader').hide();
//appends the currently uploaded images in a div
}
});
}
});
PHP
//does lot of stuff
// echo's out 2 arrays in json format which is used in appending images as stated earlier^
echo json_encode(array("images"=>$db_image_id,"src"=>$db_image_src));
Now my question is when i am choosing files to upload it automatically using #upload an #ajax-loader is shown and hidden when files are uploaded. But i want to show a progress bar in percentage and ETA(time left) replacing the simple $('#ajax-loader') . However I googled and was able to do that using ajax-form a jQuery Plugin. But i want to do in more real terms i dont want to use any PLUGINS. How will i do that ?
And one more question is whether using the #upload-form is that necesssary ?
You need to write custome xhr function to achieve tracking of progress of file uploads
$.ajax({
url: "resource/php/upload.php",
type: "POST",
data: formdata,
dataType : 'json',
processData: false,
contentType: false,
//#custome xhr
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
//#custome xhr end
success: function(data) {
$('#ajax-loader').hide();
//appends the currently uploaded images in a div
}
});
See the comment #custome xhr in above code And add a function to update progress bar
function updateProgress(evt) {
console.log('updateProgress');
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete);
} else {
// Unable to compute progress information since the total size is unknown
console.log('unable to complete');
}
}
Ref: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
Related
I have a form which allow to upload a file in AJAX. It works well, and my progress bar as well. I have 2 questions about my code :
1st : how can i make it compatible with IE 10-
2nd : There is a way to keep the progress when i'm leaving the page ? At time, my progress bar is completing well, but if i leave and return to the page, the progress bar is empty. I would like to keep the progress (eg: my progress bar shows 30%, i leave and return the page after a while, it now shows 55%) ?
My code :
$('#submitfile').click(function(event){
event.preventDefault();
var formData = new FormData($('#form-import-file')[0]);
$.ajax({
url: '{{ path('el_go_to_upload_files') }}',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
beforeSend: beforeSendHandler,
success: completeHandler,
error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
}
});
// My progress handler
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
I am relatively new to jQuery and Ajax functions, but have been working with Ajax forms over the past few days. I have come to a problem with file uploads however when trying to upload images. Whilst looking for resources, I couldn't find anything useful because they seem to be over-complicated with pointless extras or have no explanation whatsoever, which doesn't help me to learn any further.
I have wrote this code to handle the image upload in Ajax:
$(function() {
$('.input_photo').on("change",function() {
var formData = new FormData($('form.upload-form'));
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
success: function (msg) {
alert(msg)
}
});
});
});
This sends a request to the upload.php file, however no data is sent, basically my form is literally this:
<form class="upload-form">
<input type="file" name="input_photo" class="input_photo" />
</form>
No data seems to be passed in the headers whatsoever and I assume I would access it through PHP with $_POST['data'] array or $_FILES? Someone with better knowledge please help to explain this, it'd be great to understand this further.
Thanks.
This will work for one or multiple files.
$('input:file').on('change', function () {
var data = new FormData();
//Append files infos
jQuery.each($(this)[0].files, function(i, file) {
data.append('file-'+i, file);
});
$.ajax({
url: "my_path",
type: "POST",
data: data,
cache: false,
processData: false,
contentType: false,
context: this,
success: function (msg) {
alert(msg);
}
});
});
Then
$_FILES['file-0']
$_FILES['file-1']
[...]
But be careful that using FormData doesn't work on IE before IE10
You need to set processData and contentType in your ajax call ( also added id to your input element in order to fetch the file contents).
HTML
<form class="upload-form">
<input type="file" id="photo" name="input_photo" class="input_photo" />
</form>
JS
$(function() {
$('.input_photo').on("change",function() {
var file = document.getElementById("photo").files[0]; //fetch file
var formData = new FormData();
formData.append('file', file); //append file to formData object
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false, //prevent jQuery from converting your FormData into a string
contentType: false, //jQuery does not add a Content-Type header for you
success: function (msg) {
alert(msg)
}
});
});
});
Try with this:
var formData = $('form.upload-form').serialize();
I am working on building some AJAX video upload functionaliyy on my CMS, and ended up implementing the solution which was awarded the bounty here as it best suited my purposes (cross browser compatibility isn't an issue as I will only ever be managing my site via Chrome).
I've been experiencing some extremely strange behavior when I submit my form, when I var dump - the contents of my $_FILES array only includes the name parameter
The jQuery I use to submit to my upload file is as follows:
$('#confirm').click(function(){
var file = new FormData($('form')[0]);
$.ajax({
url: './app/core/commands/upload.php',
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
},
// Form data
data: file,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
Any ideas as to why my $_FILE array is empty?? I am baffled.
I have below html
This form allows you to upload a file to the server.<br>
<div class="imguploadpath" style="width:100%;height:200px;background-color:#CCC;">
<form name="myFormName" id ="myFormId" action="" method="post">
<input type="file" name="img" id = "image_pe">
<br/><br/><br/><br/>
<input id="cmdSubmit" value="Submit" type="submit" class="">
</form>
</div>
I am trying to get the file field values to upload the file in php using below script
jQuery( "#cmdSubmit" ).on( "click", function() {
var file = jQuery('#image_pe').val();
//i have to send file property to php file in jquery ajax
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
return false;
});
but var file only return some temp path c://fakepath/image.jpg
how do upload in jquery and php, I need to pass the form field in php file, I know value() jquery function is wrong.
what is the correct way to do it ?
for php file upload i was thinking of using this script http://www.tizag.com/phpT/fileupload.php
Try this:
JQuery:
var formdata = new FormData();
jQuery.each($('#image_pe')[0].files, function(i, file) {
formdata.append('image_pe', file);
});
$.ajax({
url: "/my.php",
data : formdata,
dataType : "json",
type : "post",
cache: false,
contentType: false,
processData: false,
success: function(data){
},
failure: function(){
$(this).addClass("error");
}
});
return false;
PHP Code:
$file = $_FILES['image_pe'];
Check this. This is might be very helpful for you
http://malsup.com/jquery/form/#file-upload
I need help on how to output the image and image data using php when uploaded using the code below or in other words how to handle upload with PHP
function uploadFile(blobFile, fileName) {
var fd = new FormData();
fd.append("fileToUpload", blobFile);
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response) {
// .. do something
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
}
You can use the success function to query for the image that was just uploaded. Then you can append the image to the spot on the page where you want it to be displayed.
See ajax