im trying to post image that been convert to url by using ajax. The problem is $image = $_POST['imgData'];
not show anything but if i check developer tools on network preview the data can be seen.
this is my script
var canvas = document.getElementById('chart1');
var imgData = canvas.toDataURL('image/png', 1);
//console.log(imgData);
$.ajax({
type: "POST",
url: "?f=view_customer_list",
data: { imgData: imgData },
success: function(response) {
alert(imgData);
}
});
php code
$image = $_POST['imgData'];
echo $image;
i want the url can be echo in my page
Please note that the HTMLCanvasElement.toDataURL()
method returns a data URL containing a representation of the image in the format specified by the type parameter. For further details, you may refer to documentation in mozilla
Referring to the code you posted - you have a number of things need to note and/or fix:
alert(imgData)
will not be able to display any image/graphicecho $image;
as the last line, but this will not be able to display an image by itself, you should use echo "<img src='". $image . "'>";
instead (if you want to display an image in a standalone way)imgData
will not be able to return anything from the PHP thru ajax, you should use response
instead since you are using success: function(response) { ... }
So to demonstrate how you can pass the canvas data to PHP thru ajax and then return, you can use the following
HTML
<script
src="https://code.jquery.com/jquery-3.7.1.js"
integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4="
crossorigin="anonymous"></script>
<div id=ajaxreturn></div>
<canvas id="chart1" width="200" height="100" >
<script>
var c = document.getElementById("chart1");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
</script>
<script>
var canvas = document.getElementById('chart1');
var imgData = canvas.toDataURL('image/png', 1);
//console.log(imgData);
$.ajax({
type: "POST",
url: "testajax.php",
data: { imgData: imgData },
success: function(response) {
document.getElementById('ajaxreturn').innerHTML=response;
}
});
</script>
PHP (testajax.php)
<?php
$image = $_POST['imgData'];
echo "<img src='". $image . "'>";
?>
Note:
<img src='". $image . "'>"
. Since an alert will not be display such an image, I have added a DIV with id "ajaxreturn" to the HTML so that the system can place the returned image in this DIVThe result (I captured my own browser screen dump) will be :
The lower circle is the one which we have drawn in canvas, and the upper circle is the image returned from PHP thru ajax