Question

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.

Was it helpful?

Solution

I think the error is causing because of calling the upload event even before we start initiating the XHR request.

 $.ajax({
        url:"server.php",
        beforeSend:function(xhr){
          xhr.upload.addEventListener("progress", function(event){

          });
        },
       ...

As in the code we are calling xhr.upload.addEventListener("progress" in beforeSend. Since we didn't start the request yet, (we are in beforeSend) we can't have any xhr.upload object. We can solve this by moving code to xhr instead of beforeSend.

Note: you need jQuery version > 1.5.1

$.ajax({
  url:"server.php",    
  xhr: function()
   {
   var xhr = new window.XMLHttpRequest();
   //Upload progress
   xhr.upload.addEventListener("progress", function(evt){
    ...
   }, false);
  return xhr;
 },

Here's the documentation: http://api.jquery.com/jquery.ajax/#jQuery-ajax-url-settings

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top