Saving .toDataURL() on server using PHP Error 500 - javascript

I have this function from a GitHub repo that outputs a drawn signature on canvas to a DataURL(). When I inspect it, it comes back as a string of encoded data(a .png).
The user clicks the save button and this happens:
saveButton.addEventListener("click", function (event) {
if (signaturePad.isEmpty()) {
alert("Please provide signature first.");
} else {
saveSignature(signaturePad.toDataURL());
}
});
function saveSignature(dataURL) {
$.ajax({
type: "POST",
datatype: "json",
url: "script.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
signaturePad.clear();
}
Then it triggers a PHP script in the same folder, called script.php.
<?php
// requires php5
define('UPLOAD_DIR', 'images');
$img = $_POST['imgBase64'];
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
I can't find out why it's causing a 500 server error.
The console isn't printing 'unable to save file', nor 'saved.'

You have error in script.php you are receving data in $img while write using $data so need to replace variable
<?php
// requires php5
define('UPLOAD_DIR', 'images');
$img = $_POST['imgBase64'];
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $img); //<---- change here
print $success ? $file : 'Unable to save the file.';
?>

Related

Issue with html2canvas

I need to have the child image appear in a new division it places it outside the HTML tag and cuts off bottom on save any suggestions?
I was able to get Clone to work TY for that advise... But my upload is still missing app. 50 pixels from bottom of image ..... Still have not figured out how to return the image URL back and would like to get the clone to appear Directly under my generated image and not off page..... any advise on that?
function screenshot(){
html2canvas(document.getElementById("capture")).then(function(canvas) {
var elmnt = document.getElementsByTagName("DIV")[2];
var cln = elmnt.cloneNode(true);
document.body.appendChild(cln);
// Get base64URL
var base64URL = canvas.toDataURL('image/jpg').replace('image/jpg', 'image/octet-stream');
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {image: base64URL},
success: function(data){
console.log('Upload successfully.');
}
});
});
}
Here is my ajaxfile
$image = $_POST['image'];
$location = "upload/";
$image_parts = explode(";base64,", $image);
$image_base64 = base64_decode($image_parts[1]);
date_default_timezone_set("America/Chicago");
$filename = date("m_j_y-H_i_s").'.png';
$file = $location . $filename;
$imageurl = 'upload/'.$filename.'.png';
file_put_contents($file, $image_base64);
echo $filename;
echo $file;
echo $location;
echo $image;

Store Canvas image filename and/or location path to database whilst saving?

I have a canvas image on my page with a Save button that saves down a PNG image file.
function save() {
var canvas = document.getElementById('drawing');
var dataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "canvas_ajax_upload_post.php",
data: { img: dataURL }
}).done(function(msg){
alert(msg);
});
}
The canvas_ajax_upload_post.php looks like this:
<?php
$img = $_POST['img'];
if (strpos($img, 'data:image/png;base64') === 0) {
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = 'uploads/img'.date("YmdHis").'.png';
if (file_put_contents($file, $data)) {
echo "The canvas was saved as $file.";
} else {
echo 'The canvas could not be saved.';
}
}
?>
This works fine, images get saved to the uploads folder on my server. What I have been trying to do is store the filename in my SQL database. I have a hidden form field on my main page that I would like to pass the filename or filepath to after the image has been saved, but I cannot figure out how.
I have tried embedding JavaScript code in the PHP file, but it just treats it as a text string and includes it in the alert popup. Essentially what I am trying to do is use the $file variable from the php file in JavaScript code.
E.g. document.getElementById("hidden_form_field").value = $file;
Can anybody help?
You can pass the filename in the data object:
function save() {
var canvas = document.getElementById('drawing');
var dataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "canvas_ajax_upload_post.php",
data: {
img: dataURL,
filename: document.getElementById("hidden_form_field").value
}
}).done(function(msg){
alert(msg);
});
}
Then retrieve the "filename" variable by getting $_POST["filename"]:
<?php
$img = $_POST['img'];
$filename = $_POST['filename'];
if (strpos($img, 'data:image/png;base64') === 0) {
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = 'uploads/img'.date("YmdHis").'.png';
if (file_put_contents($file, $data)) {
echo "The canvas was saved as $file.";
} else {
echo 'The canvas could not be saved.';
}
// DO SOME SQL QUERY W/ $filename variable
// SQL CODE HERE
}
?>
You'll need include your SQL query code to use the $filename variable. I didn't see that code in your question.
By what I understand from your question, you're trying to get the value of $file back form php.
You can return the value via the msg variable (which is what php echos) in your $.ajax.done function.
For example:
function(msg){
alert(msg);
if(msg.search("The canvas was saved as")!=-1){//was saved
document.getElementById("hidden_field").value=msg.slice(23);//assuming string "The canvas was saved as $file."
}
}

Canvas will not save server side PHP

I have a canvas which I need to save to a directory and store the URL in a database.
When I save the file without storing the URL in the database it works fine, and vice versa.
However, when I put the two together and specify the PHP file through AJAX, for some reason it doesn't recognise the session variable?
When I try to call the "success" on AJAX, nothing shows up. I get no response.
This could possibly be an easy fix! I think I've been staring at this code for too long.
JavaScript:
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'doodleupload.php',
type:'POST',
data:{ data:canvasData },
success: function(response){
alert(response);
//echo what the server sent back...
}
});
}
PHP:
<?php
session_start();
/* AUTOMATED VARIABLES */
$url = md5(uniqid(rand(), true));
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
$upload_dir = "images/external/doodles/";
$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
echo $success ? $file : 'Unable to save the file.';
require_once 'php/connect.php';
try
{
$stmt = $pdo->prepare("INSERT INTO posts (unique_user_id, unique_post_id, nature, image_url, timestamp) VALUE (:unique_user_id, :unique_post_id, :nature, :image_url, :timestamp)");
$stmt->bindParam(":unique_user_id",$unique_user_id);
$stmt->bindParam(":unique_post_id",$unique_post_id);
$stmt->bindParam(":nature",$nature);
$stmt->bindParam(":image_url",$imageUrl);
$stmt->bindParam(":timestamp",$timestamp);
if($stmt->execute())
{
echo "File in database";
}
else
{
echo "Not in database";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
?>
Move $upload_dir at the top, as you are calling it before you initialize it.
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';

Upload an Image using Ajax and PHP

I want to upload an image when the user clicks a button(#myid.save).Below is my code:
HTML Code:
<canvas id="cnv" width="500" height="100"></canvas>
<input id="myid_save" type="submit">Save</input>
JavaScript Code:
$('#myid_save').on('click', function(e) {
e.preventDefault();
saveViaAJAX();
});
function saveViaAJAX()
{
var testCanvas = document.getElementById("cnv");
var canvasData = testCanvas.toDataURL("image/png");
//var postData = "canvasData="+canvasData;
$.ajax({
type: "POST",
url: "testSave.php",
data: {
imgBase64: canvasData
}
}).done(function(o) {
console.log('saved');
});
}
testSave.php File:
<?php
define('UPLOAD_DIR', 'C:\xampp\htdocs\drupal-7.34\sites\all\modules\myid\uploads\id_signature');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . '\sample.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
My console says "saved" but there's no image saved in my server. Where am I missing?
testSave.php references $_POST['canvasData'], but the JS sends the intended variable as imgBase64. That line should instead read $img = $_POST['imgBase64'] in order to match the AJAX.

404 on POST but 200 on GET

I met a problem that when I make a POST request, the server responses with 404 error, while making GET request, it responses with 200.
Here are the methods that I have tried:
$.ajax({
type:"POST",
url: "script.php",
data:{
imgBase64: data
}
}).done(function(o) {
console.log('saved');
});
And:
var data = new FormData();
data.append("data" , dataURL);
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', 'script.php', true );
xhr.send(data);
Further more I have tried to include:
header("HTTP/1.0 200 OK", true);
header('Access-Control-Allow-Origin: *');
in the php script. But none of them works.
Anyone has idea? Thanks!
EDIT:
Here is the php script. By the way, I am using nodejs...
<?php
// requires php5
header('Access-Control-Allow-Origin: *');
define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$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.';
?>
I am new to nodejs and finally I found that I should write a function in server.js to process the get request.

Categories