Send a Image URL to PHP using AJAX [closed]
Technosoft Patel. The question was asked: Apr 14, 2020. 11:22
1 answer
I have converted canvas to image using DataUrl. And i am sending that URL through AJAX but on php side it shows error of Undefined index: imgBase64. I am getting error in $img variable. i have tried to echo DataURL and it perfectly works. but there must be some error in mine code of AJAX
demo.php <!DOCTYPE HTML> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> </head> <body> <canvas id="myCanvas" width="578" height="200"></canvas> <script type="text/javascript" > var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); // draw cloud context.beginPath(); context.moveTo(170, 80); context.bezierCurveTo(130, 100, 130, 150, 230, 150); context.bezierCurveTo(250, 180, 320, 180, 340, 150); context.bezierCurveTo(420, 150, 420, 120, 390, 100); context.bezierCurveTo(430, 40, 370, 30, 340, 50); context.bezierCurveTo(320, 5, 250, 20, 250, 50); context.bezierCurveTo(200, 5, 150, 20, 170, 80); context.closePath(); context.lineWidth = 5; context.fillStyle = '#8ED6FF'; context.fill(); context.strokeStyle = '#0000ff'; context.stroke(); // save canvas image as data url (png format by default) var dataURL = canvas.toDataURL(); document.write(dataURL); $.ajax({ type: "POST", url: "http://localhost/C/imagerestore.php", data: { imgBase64: dataURL } }).done(function(o) { console.log('saved'); }); </script>
imagerestore.php <?php define('UPLOAD_DIR', 'images/'); $img = $_POST['imgBase64']; $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); $data = base64_decode($img); $file = UPLOAD_DIR . uniqid() . '.png'; $success = file_put_contents($file, $data); print $success ? $file : 'Unable to save the file.'; ?>