I keep getting this error:
Uncaught TypeError: Cannot read property 'addEventListener' of undefined Where I am trying to apply an "progress" event listener
Why am I getting this error?
<script type="text/javascript">
$(document).ready(function(){
$("#wb_bc_file_field").change(function(){
var formdata = new FormData();
formdata.append("video",$("#wb_bc_file_field")[0]);
// Start Ajax Call
$.ajax({
url:"server.php",
beforeSend:function(xhr){
xhr.upload.addEventListener("progress", function(event){
});
},
processData:false,
contentType:"multipart/form-data; charset=UTF-8",
data:formdata
}).done(function(){
console.log("Request is complete.");
}).fail(function(){
console.log("Request has failed.");
}).always(function(){
console.log("Request has closed.");
}); // End .ajax
}); // End .change
}); // End .ready
</script>
Here is a jsfiddle of the entire script. Since there is no php file it will give an error but thats fine for now.
I think the error is causing because of calling the upload event even before we start initiating the XHR request.
As in the code we are calling
xhr.upload.addEventListener("progress"
inbeforeSend
. Since we didn't start the request yet, (we are inbeforeSend
) we can't have anyxhr.upload
object. We can solve this by moving code toxhr
instead ofbeforeSend
.Note: you need jQuery version > 1.5.1
Here's the documentation: http://api.jquery.com/jquery.ajax/#jQuery-ajax-url-settings