Is it possible to get status of each steps from backend? Like when I submit multipart form through ajax, it should show file upload progress, once it's finished it should show file format conversion progress then aws upload progress. Tried following ajax trick but it only show for upload progress.
$.ajax({
url: url,
type:"POST",
data: data,
processData: false,
contentType: false,
xhr: function(){
var xhr = $.ajaxSettings.xhr() ;
// set the onprogress event handler
xhr.upload.onprogress = function(evt){ console.log('progress', evt.loaded/evt.total*100) } ;
// set the onload event handler
xhr.upload.onload = function(){ console.log('DONE!') } ;
// return the customized object
return xhr ;
}
})
it's expressjs in backend. Please let me know if I'm doing it wrong or any suggestions.
Related
I have a jQuery AJAX call that appends a URL's page into a selector. I want to monitor the progress of the page being appended:
$.ajax({
url: URL,
type: 'POST',
data: {
page: 'page'
},
dataType: 'HTML',
async: true,
cache: false,
xhr:
function() {
var XHR = new window.XMLHttpRequest();
XHR.upload.addEventListener('loadstart', HandleXHR); // Upload has begun
XHR.upload.addEventListener('progress', HandleXHR); // Periodically indicates the amount of progress made so far
XHR.upload.addEventListener('error', HandleXHR); // Upload failed due to an error
XHR.upload.addEventListener('abort', HandleXHR); // Upload operation was aborted
XHR.upload.addEventListener('load', HandleXHR); // Upload completed successfully
XHR.upload.addEventListener('loadend', HandleXHR); // Upload finished
function HandleXHR(event) {
if(event.lengthComputable) {
PercentProgress = Math.floor((event.loaded / event.total) * 100);
console.log(PercentProgress); // Returns 'Content-Length' header of data object (above)
}
}
return XHR;
},
success:
function(data) {
console.log(data.length); // Returns more accurate number (probably what I want)
$('.selector').html(data);
}
});
How do I compute the correct header Content-Length information in the XHR object to show the progress status of the AJAX call success object as apposed to the header Content-Length of the data object [that I'm already getting]?
I'm using FormData and jQuery's ajax for uploading files in form.
Everything works fine except when there's no file selected on iOS, then I get error 500 from PHP script.
On PC and Android it works fine if file is or isn't selected, but on iOS it works only if file is selected (it is not required to select file).
I am using latest iOS 11.4.1.
This is my code that's called when the form is submitted:
var form = this;
var data = new FormData(form);
var options = {
url: $(form).attr('action'),
data: data,
type: $(form).attr('method'),
cache: false,
contentType: false,
processData: false,
complete: function(r){
if(r.status == 200){
var response = r.responseJSON;
showErrors(form, response.errors);
$.each(response.actions, handleAction.bind(form));
}else{
showErrors(form, ['Vyskytla sa neočkávaná chyba, skúste znova neskôr']);
}
}
};
if(data.fake){
opts.xhr = function(){
var xhr = jQuery.ajaxSettings.xhr();
xhr.send = xhr.sendAsBinary;
return xhr;
}
opts.contentType = 'multipart/form-data;boundary='+data.boundary;
opts.data = data.toString();
}
$.ajax(options);
There was a part of code that printed the response from server and this was the response:
{"readyState":4,"responseText":"\n\n\n\n
Internal Server Error
\n
The server encountered an internal error or\nmisconfiguration and was unable to complete\nyour request.
\n
Please contact the server administrator at \n ssl#atlantis.sk to inform them of the time this error occurred,\n and the actions you performed just before this error.
\n
More information about this error may be available\nin the server error log.
\n\n","status":500,"statusText":"Internal Server Error"}
I finally found the solution to my problem, it was not on the server side.
Looks like FormData puts array of one empty File object on iOS into data variable and server cannot handle that.
I edited JS to this:
var data = new FormData(form);
$.each($(form).find('input[type="file"]'), function(){
var name = $(this).attr('name');
var files = $(this).prop('files');
if(files.length == 0){
data.set(name, null);
}
});
I want to implement the following:
Call an ASHX hanlder from UI using Jquery.
Upload a file to this ASHX handler.
And when upload is complete, I want to keep sending messages from the server to UI (SSE) to tell the user about the execution status of the code in ASHX handler.
I am stuck with the 3rd point that has been mentioned above.
Following is the UI code that I have written:
var file = $("input#importFileInputHidden")[0].files[0];
var formData = new FormData();
formData.append('file', file);
importAjaxCall = $.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
$('#progressBar').show();
//Method to show the progress of the file being uploaded
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round((evt.loaded / evt.total) * 100);
$('#percentageImportComplete').text('' + percentComplete + '%');
$('#importStatus').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
type: 'post',
url: "Handler.ashx",
data: formData,
processData: false,
contentType: false,
success: function (data) {
//Some code to show success status to user
});
How to capture the messages I am sending from the server?
Have to tried to look into responseText property of http request?
success: function () {
console.log(xhr.responseText);
});
I am trying to send file to server with HTML and JavaScript. The scenario like below :
user clicks some button and it shows a div pop up.
user inputs file with <input type='file'>.
user presses button.
send data to server and div pop up closes.
Note that all of these actions happen in one page. Only div pop up can be open and closed.
At first, I was trying to send data with a <form> tag, and it works fine. The problem is when I submit the form it changes the page.
So what I am trying to do is sending file data without using a form tag. I have searched web, it looks somehow impossible. Is there any alternative way to send file data in div pop up?
Thanks :D
Have you considered doing it via JQuery?
You can post the values like this without a refresh:
$('#button').on('click', function(){
$.post('/url/to/your/function', {'post': value}, function(data){
if(data !== 0) {
}
}, "json");
});
You can find more info here
Edit:
It's not possible to upload files with jQuery $.post, neverthless, with the file API and XMLHttpRequest, it's perfectly possible to upload a file in AJAX, and you can even know how much data have been uploaded yet…
$('input').change(function()
{
var fileInput = document.querySelector('#file');
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload/');
xhr.upload.onprogress = function(e)
{
/*
* values that indicate the progression
* e.loaded
* e.total
*/
};
xhr.onload = function()
{
alert('upload complete');
};
// upload success
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0))
{
// if your server sends a message on upload sucess,
// get it with xhr.responseText
alert(xhr.responseText);
}
var form = new FormData();
form.append('title', this.files[0].name);
form.append('pict', fileInput.files[0]);
xhr.send(form);
}
More info here
I found a trick. It works, but I am not sure it is good way or not.
As you recommended, I use jQuery and ajax.
function sendUpgradeReq(id){
var url = '/api/update.json';
var form = $("#upgradeFrm");
var data = new FormData(form[0]);
$.ajax({
type : 'post',
dataType : 'json',
url : url,
data : data,
enctype : "multipart/form-data",
cache : false,
contentType : false,
processData : false,
success : function(data) {
alert('Success!');
$('#applyPop').css('display', 'none');
},
complete : function(data) {
},
error : function(data, status, error) {
alert('Fail! :<');
e.preventDefaultEvent();
}
});
}
I thought the most important part here is new FormData(). It takes complete file information from <input type='file'>.
Thanks :D
I have image upload function in my "form" which gets uploaded via ajax. So, until image is uploading, User continues to fill rest of form. and than click on submit button which is another ajax function to submit whole form.
Problem is I have below function for image upload :-
jQuery(window).load(function(){
jQuery(':button').click(function(){
var formData = new FormData(jQuery('form')[0]);
jQuery.ajax({
url: 'upload.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = jQuery.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
beforeSend: function(e) { $('#progress').css('display', 'block'); },
success: function(e) {
if (e != "no" && e != 'dir') {
$('#img').attr("src", e);
$('#imglinktosent').val(e);
} else if (e == 'dir') {
alert('Oops! We could not find \image\ directory or may be permission is not correct');
} else {
alert('File was not Uploaded, Kindly Upload Image with Size less than 512KB');
}
} ,
error: function(e) { alert('error' + e.message); } ,
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
});//]]>
It was hindering my complete form submission, therefore i changed it into Below function.
function uploadimage(){
jQuery(':button').click(function(){
var formData = jQuery('#myfile').val();
jQuery.ajax({
url: 'upload.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = jQuery.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
beforeSend: function(e) { $('#progress').css('display', 'block'); },
success: function(e) {
if (e != "no" && e != 'dir') {
$('#img').attr("src", e);
$('#imglinktosent').val(e);
} else if (e == 'dir') {
alert('Oops! We could not find \image\ directory or may be permission is not correct');
} else {
alert('File was not Uploaded, Kindly Upload Image with Size less than 512KB');
}
} ,
error: function(e) { alert('error' + e.message); } ,
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
}
So, that whenever user clicks on "upload image" button. Image will get uploaded by "uploadimage()" function set on "button" with event "onclick".
But PHP was giving error with "undefined index myfile" in upload.php
After searching for a while, i found, There was "request payload" and no formdata option in header.
After searching more in stackoverflow, i found i have to specify this too :
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
as if you would have noticed at line 30, I am sending direct formData
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
**
But I am unsure where should i specify
**
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
in my uploadimage() function to work.
Ajax doesn't support binary file transfers by default. I think it is more easy to base-64 encode your image and just post the data string to the server. You can use a html5 canvas element to get a base-64 encoded string from your image canvas.toDataURL(); . Server side you'll need to decode this string with base64_decode($yourimagedatastring);