-1

I am sending a canvas image using ajax to a php page that will catch it. Console tells me it is failing every time and not even sending. I have double checked everything and still am not seeing the issue. I finally walked away from it for a week and came back to it and for the past few hours I am still not seeing the issue. What am I over looking? The jQuery version on the server is 2.2.4

var dataURL = canvas.toDataURL();
var pngImage = new FormData();
pngImage.append('Image', dataURL);

$.ajax({
  url: 'upload.php',
  method: 'POST',
  dataType : 'text',
  data: pngImage,
  cache: false,
  contentType: false,
  processData: false,
  success: function(data) {
    console.log("sucessful send:");
    console.log(data);
  },
  error: function() {
    console.log('failed');
  }
});

UPDATE: When using

    var Grabcanvas = document.getElementById("signature");
    var ImgData = document.getElementById("Image").value = Grabcanvas.toDataURL();

    var pngImage = new FormData();

    pngImage.append('Image', $('#signature')[0].toDataURL());

    console.log(ImgData); 
    console.log(pngImage);

    $.ajax({
      url: 'upload.php',
      type: 'POST',
      dataType : 'text',
      data: pngImage,
      cache: false,
      contentType: false,
      processData: false,

      success: function(data) {
      console.log("sucessful send:");
      console.log(data);
      },
      error: function(d) {
      console.log('error');
      console.log(d);
      console.log(d.responseText);
      }

var ImgData returns the proper canvas data however var pngImage is empty and returns as FormData { } in the console.

Micha
  • 383
  • 3
  • 14
  • 1
    What happens when you get rid of these options `cache: false, contentType: false, processData: false` – Cody Caughlan Feb 22 '18 at 03:37
  • Still fails except i get the error `TypeError: 'append' called on an object that does not implement interface FormData.` – Micha Feb 22 '18 at 03:37
  • 1
    Can you post a screenshot of the console/network attempt? – Cody Caughlan Feb 22 '18 at 03:39
  • I just looked up an instance where I am sending Canvas data and I have these parameters: `contentType: false, processData: false, dataType: 'html',` – Cody Caughlan Feb 22 '18 at 03:41
  • What triggers the ajax call? What is the failure in the console? – epascarello Feb 22 '18 at 03:44
  • 1
    Try converting your ImageUrl to Blob first. See this for [reference](https://stackoverflow.com/questions/36488200/jquery-get-canvas-image-to-server) – user869375 Feb 22 '18 at 03:45
  • Check your URL. Generally, 404 occur while url is not accessible or reachable and 500 occur if the server is not responding. – Parag Soni Feb 22 '18 at 03:46
  • the only other thing the console shows me is referencing where in jQuery it is failing. `jquery.min.js:2882:39` As far as the network it only shows me that the page loaded and gave the OK 200 response. Nothing else is there meaning it isnt even submitting – Micha Feb 22 '18 at 03:47
  • Do you want to send image or whole form data ? – Casper Feb 22 '18 at 03:47
  • The signature for the `error` callback is `function(jqXHR, textStatus, errorThrown)`. Why don't you try logging some of that important data rather than just _"failed"_? Is the console telling you anything else other than _"failed"_? – Phil Feb 22 '18 at 03:51
  • you need to select your canvas element – Casper Feb 22 '18 at 03:58

3 Answers3

2

i think because you are not get correct element for pngImage.

dataToURL() i used for native javascript dom, not jquery dom.

this means if id of canvas is #canvas, you should doing this:

var pngImage = new FormData();
        pngImage.append('Image', document.getElementById('canvas').toDataURL());

or in jquery

    pngImage.append('Image', $('canvas')[0].toDataURL());

so our code will be like below:

<canvas id="canvas" width="5" height="5"></canvas>
    <script src="jquery-3.3.1.min.js"></script>
    <script>
    $(function(){
        var pngImage = new FormData();
        pngImage.append('Image', $('#canvas')[0].toDataURL());
        
        $.ajax({
          url: 'upload.php',
          type: 'POST',
          dataType : 'text',
          data: pngImage,
          cache: false,
          contentType: false,
          processData: false,
          success: function(data) {
            console.log("sucessful send:");
            console.log(data);
          },
          error: function(d) {
            console.log('error');
            console.log(d); //show error
            console.log(d.responseText); //show error reponse text
          }
        });
    })
    </script>

php

<?php print_r($_POST);?>

you will see

sucessful send:
Array
(
    [Image] => data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC
)

UPDATE:

sry i need to lunch first ^_^

  1. why you cant catch POST using $_POST? because you miss write the syntax, and i copy paste your code without read carefully. (so, this is lucky for me to use $_REQUEST XD)

method: 'POST' => no method named as method in jquery ajax. the right method is type: 'POST' , then you can catch it using $_POST. (try to change to $_GET too for learning)

huft... how can i miss that

  1. you want upload image using binary/blob style but your data is actually just string/text. in this case, i really prefer doing this way

.

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<canvas id="canvas" width="5" height="5"></canvas>
<script>
$(function(){
    $.ajax({
      url: 'upload.php',
      type: 'POST',
      data: {Image: $('#canvas')[0].toDataURL()},
      success: function(data) {
        console.log(data);
      },
      error: function(d) {
        console.log('error');
      }
    });
})
</script>

PHP

<?php print_r($_POST);?>
Community
  • 1
  • 1
plonknimbuzz
  • 2,594
  • 2
  • 19
  • 31
  • Say something about your answer how and why this address op's question? – 4b0 Feb 22 '18 at 03:55
  • Its definitely sending now. Errors are gone and its transmitting data. I just have to rewrite the php to catch the data. I am guessing due to it sending an array I can just catch it with a `$_REQUEST`? I very much thank you. You solved the issue I have had in seconds. Much appreciated – Micha Feb 22 '18 at 04:17
  • @Micha `$_REQUEST` is catch POST and GET. `$_GET` only for GET, `$_POST` only for POST. why i using $_REQUEST instead $_POST? because i want to use it for no reason. really for no reason. the right way is using $_POST, because we using `method: 'POST'` in our ajax – plonknimbuzz Feb 22 '18 at 04:41
  • I was asking as `$img = $_POST['Image'];` wasn't returning results to me. I have never has to retrieve an array so I was a bit unclear. Unless as it is an array I need to grab it by key and id such as `$img = $_POST['Image'][0];` – Micha Feb 22 '18 at 04:51
  • @plonknimbuzz I am seeing there is many differences between jQuery and javascript. Good to know. I really appreciate the time you took to help and educate me on this. Thank you – Micha Feb 22 '18 at 19:06
  • I do notice everything sends fine however the array in the `console.log` is empty. no data is being sent. The canvas is being called by id and when i set an alert to show the canvas it shows fine as well. I dont get it. How could the value be empty? – Micha Feb 22 '18 at 21:08
  • you can open new thread. because thats will be different according to your main question. and the main things is, you need to post your code and the explaination – plonknimbuzz Feb 22 '18 at 22:52
0

For an example think this is your element,

<canvas id="canvas" width="5" height="5"></canvas>

Now you need to select this element,

var canvas = document.getElementById('canvas');

And

var dataURL = canvas.toDataURL();

Then you can send via Ajax

$.ajax({
   url: 'a.php',
   method: 'POST',
   data: dataURL,
   success: function(data) {
      console.log("sucessful send:");
      console.log(data);
   },
   error: function(d) {
      console.log('error');
      console.log(d); //show error
      console.log(d.responseText); //show error reponse text
   }
});
Casper
  • 1,469
  • 10
  • 19
0

So for those of you that are having trouble with sending an image from a canvas through AJAX here is an answer. Nobody would give me correct information on here or just wanted to be jerks and keep down voting. I found someone nice enough somewhere else to explain my issue. When the canvas is converted to a dataURL using toDataURL() you have to remove data:image/png;base64, from the dataURL string or it will not send. This was acheived by a simple line which is var png = ImgData.split(',')[1]; The data now sends no problem and can be picked up in PHP and converted no problem. I sincerely hope this helps someone in the future as it caused me a lot of issues getting a CORRECT answer.

var Grabcanvas = document.getElementById("signature");

var ImgData = Grabcanvas.toDataURL();

var png = ImgData.split(',')[1]; //THIS IS WHAT DID IT

$.ajax({
  url: 'upload.php',
  type: 'POST',
  dataType : 'text',
  contentType: "application/x-www-form-urlencoded; charset=UTF-8",
  data: {"Image" : png},

  success: function(data) {
  console.log("sucessful send:");
  console.log(data);
  },
  error: function(d) {
  console.log('error');
  console.log(d);
  console.log(d.responseText);
  }
Micha
  • 383
  • 3
  • 14