Uniquely identify an upload - javascript

I'm uploading files using the following code:
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.open("POST", requestUrl, true);
xhr.send(f);
Note that I'm attaching a listener to upload progress:
function uploadProgress(evt)
{
// Which upload was it?
}
Here's the question, if I have multiple uploads happening at the same time, and they are sharing the same event handler, how can I figure out which upload triggered the event?

Try to wrap it as a Control?
var uploadProgress = function(uploadObj, event) {
// Do somthing about uploadObj
}
// Target maybe object or string, whatever you want
var Uploader = function(target) {
var xhr = new XMLHttpRequest();
var handler = uploadProgress.bind(this, target);
xhr.upload.addEventListener("progress", handler, false);
xhr.open("POST", target, true);
xhr.send(f);
}
The .bind will return a new function, when execute the new function, it'll:
Use this here, the Uploader as its context.
Execute uploadProgress and pass target as first argument, so the evt given by progess event will be passed to the 2nd param in uploadProgress.

Related

AJAX : What is the equivalent function of beforeSend function in XMLHttpRequest

In $.ajax there is beforeSend function, but now I'm trying to use XMLHttpRequest, I'm looking for equivalent function of beforeSend in $.ajax. How can i implement it in here.
Here is my xhr code,
xhr = new XMLHttpRequest();
var url = '../ajax/ajax_edit/update_ajax_staffUser.php';
if(file.files.length !== 0){
if(!check(fileUpload.type)){
alert("This file format not accepted");
return false;
}
xhr.open('post', url+param, true);
xhr.setRequestHeader('Content-Type','multipart/form-data');
xhr.setRequestHeader('X-File-Name', fileUpload.name);
xhr.setRequestHeader('X-File-Size', fileUpload.size);
xhr.setRequestHeader('X-File-Type', fileUpload.type);
xhr.send(fileUpload);
}else{
xhr.open('post', url+param, true);
xhr.setRequestHeader('Content-Type','multipart/form-data');
xhr.send(fileUpload);
}
xhr.onreadystatechange = function(e){
if(xhr.readyState===4){
if(xhr.status==200){
$('.bounce_dim').show();
setTimeout(function(){
$('.trigger_danger_alert_changable_success').show().delay(5000).fadeOut();
$('#palitan_ng_text_success').html('User successfully modified');
$('#frm_edit_staffUser')[0].reset();
$('#modal_staff').modal('hide');
$('.bounce_dim').hide();
},1000);
getUserStaffTable();
}
}
}
Since the users are uploading image to my web, I need to make a waiting interface before fires the call since the image size are too large.
You can do this by just putting the beforeSend() function before your XHR intantiation, like this:
beforeSend();
xhr = new XMLHttpRequest();
But you should define your beforeSend() function before the code above:
var beforeSend = function(){
// your code here
}
.beforeSend just calls the function before running .send, so just put your code before the line:
xhr.setRequestHeader('Content-Type','multipart/form-data');
xhr.setRequestHeader('X-File-Name', fileUpload.name);
xhr.setRequestHeader('X-File-Size', fileUpload.size);
xhr.setRequestHeader('X-File-Type', fileUpload.type);
beforeSend(); // Put any code to run before sending here
xhr.send(fileUpload);

Angularjs HTTP service POST progress event

Since most topics about this subject are over a year old, I asked myself if there are any good solutions to track an ajax progress event from an http service (for a loading bar or to track how many bytes it has downloaded). Without the use of 3rd parties :)
these events:
var ajax = new XMLHttpRequest();
ajax.addEventListener("progress")
ajax.addEventListener("load")
ajax.addEventListener("error")
ajax.addEventListener("abort")
I've made something like that using a promise with notify for the progress :
var deferred = $q.defer();
var fd = new FormData();
fd.append("Filename", file.name);
fd.append("file", file);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", function (event) {
deferred.notify(event);
}, false);
xhr.addEventListener("load", function (data) {
deferred.resolve(event.target.response);
}, false);
xhr.addEventListener("error", function (data) {
deferred.reject(event.target.response);
}, false);
xhr.addEventListener("abort", function (data) {
deferred.reject(event.target.response);
}, false);
xhr.open("POST", URL);
xhr.send(fd);
return deferred.promise;

sending arguments from one function to another through event handler

I have two functions here, the first one is triggered by a button and it is meant to trigger a second function which will change the inner html of that first buttons accompanying html area.
My problem is how to pass the arguments from the first function INTO the second one to the button and textfield have the same idnumber.
function doLoad(idnumber, id) {
var file = _(id).files[0];
_("Btn1_QP_"+idnumber).style.display = "none";
_("Display_QP_"+idnumber).innerHTML = "Image uploading......";
var formdata = new FormData();
formdata.append("stPic", file);
var ajax = new XMLHttpRequest();
ajax.addEventListener("load", completeHandler, false);
ajax.open("POST", "pho_stem3.php");
ajax.send(formdata);
}
function completeHandler(event) {
_("Display_QP").innerHTML = 'wahooo';
}
}
In function doLoad idnumber is given by the button and used to identify the proper button with("Btn1_QP_"+idnumber)
how can i achieve this same selective ability in the second function completeHandler in the event listener.
I have tried
ajax.addEventListener("load", completeHandler(idnumber), false);
ajax.addEventListener("load", ("completeHandler"+idnumber), false);
both dont work. how can i preserve and transmit the original argument from doLoad...
You can pass the same id number in response of ajax like this:
function doLoad(idnumber, id) {
var file = _(id).files[0];
_("Btn1_QP_" + idnumber).style.display = "none";
_("Display_QP_" + idnumber).innerHTML = "Image uploading......";
var formdata = new FormData();
formdata.append("stPic", file);
var ajax = new XMLHttpRequest();
ajax.open("POST", "pho_stem3.php");
ajax.send(formdata);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
completeHandler(idnumber);
}
}
}
function completeHandler(idnumber) {
_("Display_QP_" + idnumber).innerHTM = 'wahooo';
}

Getting a document Object from url of an html page

I`am working on a js file which was designed for a home page.
I would like to navigate from this page to other pages via a navigation menu bar.
The target pages are sharing the same templat(a html code), thus for going to a specific page I need to load a specific content, which is saved in a xml file, then pass its contents to the target page.
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.send(null);
}
catch (e) {
window.alert("Unable to load the requested file.");
}
// Until this point I can load the specific content
// How can I get from the url of the target page
// a js document object, so that I can call getElementById(Id)
// to pass the specific content.
// For instance: Im currently opnening X1:= www.main.com
// und I would like to switch to X2 := www.targetpage.com
// target page which contains html the templat.
// The problem **document** represents currently X1
// but i would like to set it to X2 so that I can pass
// the content of xhr.responseText to it
var component = **document**.getElementById(elementId);
component.innerHTML = xhr.responseText;
}
Thanks
Try this, I have added xhr.onload function, which populated text returned from response
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.onload = function () {
var component = document.getElementById(elementId);
component.innerHTML = xhr.responseText;
}
xhr.send(null);
}
catch (e) {
window.alert("Unable to load the requested file.");
}
}
You can also use onreadystatechange event instead of onload. click for more reference
Try this
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.onload = function () {
var com = document.getElementById(elementId);
com.innerHTML = xhr.responseText;
}
xhr.send();
}
catch (e) {
window.alert("Unable to load the requested file.");
}
}
Reference

Append array element to FormData doesn't work in Firefox 15

I'm making crossdomain ajax post request.
There is the client function:
function getUsersData()
{
var ids = ["user1_id", "user2_id"];
var fd = new FormData();
$.each(ids, function() {
fd.append('identities', this);
});
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://some-domain.com/Home/GetUsersData', true);
xhr.withCredentials = true;
xhr.onreadystatechange = responseHandler; //function is defined and not shown here
xhr.send(fd);
}
Everything works fine in Opera and Google Chrome browsers.
But Firefox says NS_ERROR_CANNOT_CONVERT_DATA: Component returned failure code: 0x80460001 (NS_ERROR_CANNOT_CONVERT_DATA) [nsIDOMFormData.append] at the line fd.append('identities', this);
What it can be and how to fix this error?
Try to use unique keys. Something like: fd.append('identity-'+this.id, this);

Categories

Resources