INOH INOH - 2 months ago 6
Ajax Question

Send formData seperatly

Ok this is what I am trying to acchomplish, (As of Now)I have user select image and the image is resized and uploaded to server. What i would like to do is after the image is selected and resized then stop Script. Then i would like to create a function to upload resized image when i choose to. The reason is that i am going to add more inputs texts into my form and was user has finished completing I then want to upload image with the files. Note: I have not added the text inputs will do after just want to be able to sepearate the upload functions..I am not sure how to seperate the FormData post portion

JAVASCRIPT

<script>
function ResizeMe(){
var dataurl = null;
var uniq = 'id' + (new Date()).getTime();
var filesToUpload = document.getElementById('input').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;

img.onload = function () {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);

var MAX_WIDTH = 200;
var MAX_HEIGHT = 400;
var width = img.width;
var height = img.height;

if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > 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);
dataurl = canvas.toDataURL("image/jpeg",.2);
var blobBin = atob(dataurl.split(',')[1]);
var array = [];
for(var i = 0; i < blobBin.length; i++) {
array.push(blobBin.charCodeAt(i));
}
var files = new Blob([new Uint8Array(array)], {type: 'image/jpg', name: "ddd"});
// Post the data
var fd = new FormData();
fd.append("image", files, uniq);
$.ajax({
url: 'http:///www.***/upload.php',
data: fd,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
$('#form_input')[0].reset();
location.reload();
}
});
} // img.onload
}
// Load files into file reader
reader.readAsDataURL(file);
}
</script>

Answer

The code sending the formdata is

$.ajax({
    url: 'http:///www.***/upload.php',
    data: fd,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        $('#form_input')[0].reset();
        location.reload();
    }
});

That code is the code that you will want to put in a separate function. To move it elsewhere, you have to make sure it still has access to all of the variables being sent, namely, fd. fd is connected to several variables, all leading back to canvas. You say that there will only be one canvas at a time, so we can make canvas a global variable, and then getting fd from anywhere will be easy.

<script>
  //Moved to global so that sendFormStuff will see it
  var canvas = document.createElement("canvas");
  var ctx = canvas.getContext("2d");
  function ResizeMe(){
    var dataurl = null;
    var uniq = 'id' + (new Date()).getTime();
    var filesToUpload = document.getElementById('input').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;

      img.onload = function () {

        ctx.drawImage(img, 0, 0);

        var MAX_WIDTH = 200;
        var MAX_HEIGHT = 400;
        var width = img.width;
        var height = img.height;

        if (width > height) {
          if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
          }
        } else {
          if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
          }
        }
        canvas.width = width;
        canvas.height = height;
        ctx.drawImage(img, 0, 0, width, height);
      } // img.onload
    }
    function sendFormStuff() {
      var dataurl = canvas.toDataURL("image/jpeg",.2);
      var blobBin = atob(dataurl.split(',')[1]);
      var array = [];
      for(var i = 0; i < blobBin.length; i++) {
        array.push(blobBin.charCodeAt(i));
      }
      var files = new Blob([new Uint8Array(array)], {type: 'image/jpg', name: "ddd"});
      // Post the data
      var fd = new FormData();
      fd.append("image", files, uniq);
      $.ajax({
        url: 'http:///www.***/upload.php',
        data: fd,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(data){
          $('#form_input')[0].reset();
          location.reload();
        }
      });
    }
    // Load files into file reader
    reader.readAsDataURL(file);
  }
</script>

So really all we did here was move the request code into a separate function, and make canvas and ctx (which you were declaring twice, btw) accessible by that function.