I have the following piece of code. The string is being sent to uploadFile correctly but the line alert(str) is giving me undefined?
function uploadFile(str){
alert(str); //prints correctly
var fileTag = document.getElementById('fileinput');
var file = fileTag.files[0];
var xmlhttp=new XMLHttpRequest();
var formData = new FormData();
formData.append("thefile", file);
xmlhttp.addEventListener("load", function(evt,str){
alert(str); //undefined
}, false);
....
}
I’m fairly new to javascript, so can anyone tell me why this is happening? thank you
The event handler function receives a single parameter: an
eventobject.Your event handler
expects two parameters. Naturally, as it doesn’t receive the second one,
str, you get thatstris undefined.If you want your event handler to use the
strvariable which is defined as a parameter offunction uploadFile(str){ }, however, you can do that, because the evet handler function is defined inside theuploadFile(str){ }function. This is called a closure. Just changeto
This way, you remove the inner definition of
str, which hided the outer one, inuploadFile(str). So inyou will really get the alert of the string
str.