title: Setting hidden input value to a dataURL on form submit using jQuery
body: <p>I'm using jQuery to take take an image file from an input form, resize it in an HTML5 canvas, and convert the resized image to a dataURL. However, I can't figure out how to set the hidden input's value to the dataURL. </p>
  
  <p>I've confirmed I can see the dataURL using console.log in the img.onload function, but not if I use console.log anywhere outside of the function. This is why I'm submitting the form inside img.onload. However, the value is always "Not set" when it hits the server.</p>
  
  <pre><code>&lt;form id='upForm' enctype="multipart/form-data" action="" method="post"&gt;
      &lt;table&gt;
          &lt;tr&gt;&lt;th&gt;&lt;label for="id_file"&gt;File:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;input id="id_file" name="file" type="file" /&gt;&lt;/td&gt;&lt;/tr&gt;
      &lt;/table&gt;
      &lt;input type='hidden' name='csrfmiddlewaretoken' value='rLSVnSf35kwe9Yvq7P85lqmcp3LmC77J' /&gt;
      &lt;BR&gt;        
      &lt;input type="hidden" id="myData" name="dataURL" value="Not set" /&gt;
      &lt;input type="submit" name="sendFile" id="sendButton" value="Submit" class="btn btn-lg btn-primary"&gt;
  &lt;/form&gt;
  
  &lt;script&gt;
  $('#upForm').submit(function(e) {
      e.preventDefault();
  
      var self = this;
      var img = document.createElement("img");
      var reader = new FileReader();
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      var dataURL = ""
  
      img.onload = function() {
          ctx.drawImage(img, 0, 0, 600, 800);
          dataURL = canvas.toDataURL("image/jpeg", 1.0);
          $('#myData').attr('value', dataURL);
          self.submit();}
  
      reader.onload = function(event) {
          img.src = event.target.result;}
  
      reader.readAsDataURL($('#id_file')[0].files[0]);
  
      $('#main').html('&lt;P&gt;Uploading receipt.&lt;P&gt;&lt;img src=\"/static/receipts/loading.gif\"&gt;');
      });
  </code></pre>
  
  <p></p>