title: Resize and upload picture via Ajax
body: <p>I have this code that resize the image and I want it to upload after resizing photo and submit the form using Ajax. I tried doing it but, it doesn't seems to resize my photo. I'm new to Javascript, please guide me. Below is my code:-</p>
  
  <pre><code>    &lt;form id="imgLocal" name="imgLocal" accept-charset="utf-8" enctype="multipart/form-data"&gt;
      &lt;input type="file" name="receipt" id="receipt" accept="images/*" onchange="handleFiles();" /&gt;
      &lt;/form&gt;
  
      // Form validation above
  
      submitHandler:function(form) {
      var formData = new FormData(form);
                  $.ajax({
                  type: 'POST',
                  url: 'a/imgUpload',
                  dataType: 'json',
                  data: formData,
                  cache: false,
                  contentType: false,
                  processData: false
                  }).success(function(data){
                      show('loading', false);
                      alert('success');
                  }else {
                     alert('error');
  }
  
          function handleFiles()
          {
              var filesToUpload = document.getElementById('receipt').files;
              var file = filesToUpload[0];
  
              // Create an image
              var img = document.createElement("img");
              // Create a file reader
              var reader = new FileReader();
              // Set the image once loaded into file reader
              reader.onload = function(e)
              {
                  img.src = e.target.result;
  
                  var canvas = document.createElement("canvas");
                  //var canvas = $("&lt;canvas&gt;", {"id":"testing"})[0];
                  var ctx = canvas.getContext("2d");
                  ctx.drawImage(img, 0, 0);
  
                  var MAX_WIDTH = 400;
                  var MAX_HEIGHT = 300;
                  var width = img.width;
                  var height = img.height;
  
                  if (width &gt; height) {
                    if (width &gt; MAX_WIDTH) {
                      height *= MAX_WIDTH / width;
                      width = MAX_WIDTH;
                    }
                  } else {
                    if (height &gt; MAX_HEIGHT) {
                      width *= MAX_HEIGHT / height;
                      height = MAX_HEIGHT;
                    }
                  }
                  canvas.width = width;
                  canvas.height = height;
                  var ctx = canvas.getContext("2d");
                  ctx.drawImage(img, 0, 0, width, height);
  
                  var dataurl = canvas.toDataURL("image/png");
                    $('#receipt').attr('value', dataurl); 
              }
              reader.readAsDataURL(file);
  
          }
      }
  </code></pre>