Implement SSE (Server Sent Events) with File Upload to ASHX Handler - javascript

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

Related

Get status of form submission from backend

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.

Jquery file uploading progress bar

Im uploading video and image files with progress bar using jquery ajax. Im using server side form validation and check duplicate entry. My issue is validation error message show after progress bar becomes complete. I want something like this...
if form validation is correct
then show progress bar
else if form validation is not correct
then only show error message of form validation
else if duplicate entry
then only show error message of duplicate entry
this is my js code:
$.ajax({
url: ajaxUrl,
type: 'POST',
dataType: 'json',
processData: false,
contentType: false,
async: true,
data: formData,
xhr: function () {
//upload Progress
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
var temp = event.loaded/event.total*100;
//update progressbar
$('div#upload-progress').text(percent + "%");
$('div#upload-progress').css("width", + temp + "%");
}, true);
}
return xhr;
},
complete: function(xhr) {
if(xhr.responseText) {
//console.log(xhr);
}
},
success: function(data, status){
if (data.hasOwnProperty('form-error')) {
$.each(data['form-error'], function (key, value) {
$("span#span_" + key).text(value);
})
} else {
// Form validation is correct
}
},
error : function(xhr, textStatus, errorThrown) {
var data = xhr.responseText;
myWindow = window.open("data:text/html," + encodeURIComponent(data), "parent", "width=1000, height=600");
myWindow.focus();
}
});
Can anyone give me any suggestion to how to do this?
If you're using the server to validate the file, that means that the file will have to be uploaded first before you can validate it, hence why you see the progress bar first. If you only want to check for duplicates (based on filename, size etc.), you need 2 ajax requests:
Send only the filename & size and validate it.
If valid, upload the file. (and validate again, of course)
Just my 2 cents.
I did made a AJAX file upload with a progress bar, you might want to take a look? I guess?
https://github.com/felixfong227/fileupload/blob/master/static/js/index.js

jQuery's "uploadProgress" not firing in "$.ajax"

I am new to jQuery and now, I am currently working on file uploads. And I want to add some progress bar each time I upload image. I used the uploadProgress in jQuery but it seems doesn't work. Here's my code:
$('#_form_').on('submit', function(e){
var file_and_desc = new FormData($(this)[0]),
form_url = "_pages/_form_";
var ext = choose.val(),
allowed = ['jpg','png'];
if(ext){
var get_ext = ext.split('.');
get_ext.reverse();
if($.inArray(get_ext[0].toLowerCase(), allowed) > -1){
//upload image
$.ajax({
url : form_url,
type: 'POST',
data: file_and_desc,
contentType: false,
processData: false,
uploadProgress: function(event, positio, total, percentComplete){
$('h1').html(percentComplete);
},
success: function(data){
// some code here...
}
});
}
}
});
That's it! What should I do?
According to the $.ajax() reference, uploadProgress is not a valid option.
Instead, the xhr option is used instead, which lets you set progress listeners on the XMLHttpRequest that is used by the ajax request.
this answer shows how to do that:
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
//Do something with upload progress here
}
}, false);
return xhr;
},
type: 'POST',
url: "/",
data: {},
success: function(data){
//Do something on success
}
});

jQuery, ajax .done fired late?

did anyone have an idea why the:
success, complete and done
event fired 5-10 seconds later than the "xhr.upload.addEventListener("load")" event?
What is the correct event?
iam not shure, which time the correct upload-time is?
hope, that somebody can help me :)
greets
paD
$('body').on('change', '#fileUploader', function() {
// Post-Daten vorbereiten
//var data = new FormData();
//data.append('file', this.files[0]);
var xhr = new XMLHttpRequest();
var data = new FormData();
var files = $("#fileUploader").get(0).files;
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
// Ajax-Call
$.ajax({
url: '<?=$this->language->modulLink('Upload/DoUpload');?>',
data: data,
type: 'POST',
cache: false,
processData: false,
contentType: false,
success: function() {
console.log("JETZT");
},
complete: function(){
console.log( "action finished" );
},
xhr: function() {
var xhr = $.ajaxSettings.xhr();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete + ' :: ' + evt.loaded + ' :: ' + evt.total);
//Do something with upload progress here
}
}, false);
xhr.upload.addEventListener("load", function(evt) {
console.log("rdy");
}, false);
return xhr;
},
}).done(function(d) { console.log(d); });
});
It's because you are making AJAX call which is asynchronous. Ajax sends the Request from the client side and without waiting for the response starts executing the code statements written(in your case event listener) after the AJAX call code statement. Then once it receives the response from server, based on the response it executes either the success/failure method.
(1.) Ajax call is sent
-->
(2.) Statements after the AJAX call (i.e eventlistener method) are executed
-->
(3.) Server finally responds to AJAX call
-->
(4.) Success method of AJAX call is executed
I recommend you to go through this tutorials. AJAX

How to send a string along with file via ajax request to a php file?

I got a php file that saves file to server to a folder called upload it receives file via an ajax request every thing works fine so far the next requirement is to send a string along with the file to specify an upload folder & sub folder like "Course/Math" how to achieve that?
JS
$( document ).ready(function() {
$('#Upload').click(function(){
var formData = new FormData($('form')[0]);
$.ajax({
url: 'uploadFile.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandling, false);
}
return myXhr;
},
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
});
var progressHandling = function(e){
if(e.lengthComputable){
var percent = Math.round((e.loaded / e.total) * 100);
$('#uploadprogress').css('width', percent+'%');
}
}
var completeHandler = function(data){
$('#message').text(data);
$('#uploadprogress').css('width', '0%');
$('#file').val('');
};
});
PHP
<?php
if ($_FILES["file"]["error"] > 0) {
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo true;
}
?>
Sample Example of Sending form data in ajax call with .serialize()
var formData = $('#myform').serialize;
$.ajax({
url: 'uploadFile.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandling, false);
}
return myXhr;
},
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
If you want to add a string simply use like following:
var value = 'test';
var formData = $('#myform').serialize+"&newstring="+value;
Update
File upload is not possible through ajax.
You can upload file, without refreshing page by using IFrame or AjaxFileUpload Plugin.
Further Details here is Answer.
Also file some detail explanation here also:
jQuery Ajax File Upload
jQuery Upload Progress and AJAX file upload
You could use the HTML5 Upload element.
$("#FileUpload").change(function (e) {
var uploadFile = e.target.files;
if (uploadFile.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < uploadFile.length; x++) {
data.append("file" + x, uploadFile[x]);
}
data.append("ELEMENTCLASSNAME", $("#ELEMENTID").val());
$.ajax({
type: "POST",
url: 'URL',
contentType: false,
processData: false,
data: data,
success: function (result) {
alert(result);
},
failure: function (result) {
alert(result);
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
} else {
alert("This browser doesn't support HTML5 file uploads!");
}
}});
On the server side use the Request Object get the value:
var versionName = Request["ELEMENTCLASSNAME"];

Categories