I'm using kinetic js to create a canvas and it also saves the canvas to an image file using this ajax:
stage.toDataURL({
callback: function(dataUrl) {
var url = 'export.php';
$.ajax({
type: "POST",
url: url,
dataType: 'text',
data: {
base64data : dataUrl
}
});
I need to also pass some form variables to export.php - whats the best way to do that?
Thanks!
Zoe
Your JS part is correct:
function upload() {
stage.toDataURL({
callback: function (dataUrl) {
$.ajax({
type: "POST",
url: 'export.php',
dataType: 'text',
data: {
base64data: dataUrl
}
});
}
});
}
In PHP, data arrive with the following pattern: 'data:image/png;base64,...characters'; ... So you have to extract the image part.
<?php
$data = $_POST['base64data'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
file_put_contents('image.png', $data);
Note that this solution is not specific to kineticjs. It can be used with any HTML5 canvas, provided that you replace stage.toDataURL() call by canvas.toDataURL().
Related
So I am having some issues using jQuery to POST data to a php script. I am passing the image data from a canvas to php that will in turn save the image to the server. I am wanting this to stay as a string when sending to make it easy when the php gets it. I have tried send in json as well and no success with that. The issue is I am not getting anything in return. I have no errors in the console and php isn't leaving any errors for me either to find. I also am for the time being writing the info passed to a txt file as well to verify that data is being passed and it as well is empty. What am I doing wrong? Also I have verified the DataURL var has info in it using an alert and it contains a nice string.
var dataURL = Grabcanvas.toDataURL();
$.ajax({
url: 'upload.php',
method: 'POST',
dataType : 'text',
data: {Image:dataURL},
success : function(data) {
console.log("sucessfull sending:");
console.log(data);
},
error : function() {
console.log('failed');
}
The php code
$writeDir = "dir/text/";
$upload_dir = "dir/image/";
$img = $_REQUEST['Image'];
$myfile = fopen($writeDir."newfile.txt", "w") or die("Unable to open file!");
$txt = $img . "\n";
fwrite($myfile, $txt);
fclose($myfile);
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . mktime() . ".png";
file_put_contents($file, $data);
In your ajax call you have the key as Image {Image:dataURL} but in your php script your trying to access image $_REQUEST['image'], the key is case sensitive. change the one in ajax to image
you may try this
var dataURL = Grabcanvas.toDataURL();
var data = new FormData(); // added this line
data.append('Image', dataURL); // I have added this line
$.ajax({
url: 'upload.php',
method: 'POST',
dataType : 'text',
data: data, //I have changed this
success : function(data) {
console.log("sucessfull sending:");
console.log(data);
},
error : function() {
console.log('failed');
}
In PHP code change the following
$img = $_REQUEST['Image']; //you have used image, mind it it is case sensitive
This fixed it. Apparently I was explained to by a user here that toDataURL() is used for native javascript DOM but not jQuery DOM which I am using jQuery. So after code was rewritten to reflect this it now works correctly and sends without failing
`$.ajax({
url: 'upload.php',
type: 'POST',
dataType : 'text',
data: {Image: $('#name of canvas')[0].toDataURL()}, //CHANGED
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);
}`
I am doing an ajax popup to upload image into filesystem. The image uploading process has the following steps..
choosing the file and crop it to needed size.
the result image is displayed in <img> tag src as Base64 Code.
converting the Base64 to Blob to send via ajax
Here is the code...
$(document).ready(function(){
$('#btn_save').on('click', function () {
var PaymentStatus = $("#PaymentStatus").val();
var image = $('#image-id').val();
var base64ImageContent = image.replace(/^data:image\/(png|jpg);base64,/, "");
var blob = base64ToBlob(base64ImageContent, 'image/png');
var formData = new FormData();
formData.append('picture', blob);
formData.append('PaymentStatus', PaymentStatus);
$.ajax({
data: formData,
url:"/login/advshop/add",
method: 'GET',
processData: false,
contentType: false,
success: function (result) {
alert("form submitted");
},
error: function (result) {
alert('error');
//alert(result);
}
});
});
});
but I am not able to get the data in my controller..
public function add() {
print_r($_POST['picture']);
}
and the error message is..
Message: Undefined index: picture
please see my answer..
$(document).ready(function () {
$('#btn_save').on('click', function () {
var image = $('#image-id').val();
var base64ImageContent = image.replace(/^data:image\/(png|jpg);base64,/, "");
var PaymentStatus = $("#PaymentStatus").val();
var formData = new FormData();
formData.append('image', base64ImageContent);
formData.append('PaymentStatus', PaymentStatus);
$.ajax({
data: formData,
url: "/login/advshop/add",
method: 'POST',
processData: false,
contentType: false,
success: function (result) {
alert("form submitted");
},
error: function (result) {
alert('error');
//alert(result);
}
});
});
})
In Controller.
public function add() {
$data = base64_decode($_POST['image']);
file_put_contents('images/test.jpg', $data);
}
you can directly pass the Base64 image content via ajax using formData append.decode the base64 content and put it in file_put_contents() function.
i think the issue is that you wanna convert the uploaded image into base64 string and then you wanna pass this string to controller via ajax ..is it brother..
i too faced that problem..so first take a hiddenfield in your form and give id and value for hiddenfield as value of hidden field is the converted string .then you can easily get the value of hiddenfield i.e. base64 string into a variable in js by getElementById then pass the variable to controller..there youcan access through $_POST['id of hiddenfield']. then you can store the value into database directly by save().
yes ,no need to convert base64 to string..base64 returns string so u use this string to value of hiddenfield.
I want to update the json file by overwriting the old one. I can export the data to a json string by using some jquery. And the data is stored in the variable json_update . But I don't know how to send the data to php.
$(function () {
$('#switcher').click(function () {
var json_update = JSON.stringify($('#table-hover').bootstrapTable('getData'));
$.ajax({
type: "POST",
url: "adding2.php",
data: json_update,
contentType: "application/json; charset=utf-8"
dataType: "json",
success: function (data) {
alert("success");
}
});
});
});
And here is the adding2.php . Thanks for helping me.
<?php
$data = $_POST['json_update'];
$fileHandler = fopen('work2.json', 'w+');
fwrite('work2.json',$data);
fclose($fileHandler);
?>
Give the data a parameter name before sending it:
var json_update = { json_update: JSON.stringify($('#table-hover').bootstrapTable('getData')) };
This will make it accessible in $_POST['json_update']
The data you send from the client side (the value of json_update) is stored in $_POST, so just change $data = $_POST['json_update']; to $data = $_POST;.
I know this question was already here a lot, but none of solutions looks to be working for me.
So, I am using Kinetics.js and I have build an canvas application where people can draw their images (pretty simple). The idea is that when image is ready user would go to the next page, but I need his drawing to be saved as a file at server.
Here is my code:
JavaScript:
$('#someButton').click(function(){
hiddenCanvas.toDataURL({
callback:function(dataUrl){
$.ajax({
type: "POST",
url: "scripts/imgsave.php",
data: {image: dataURL}
});
}
});
window.location = 'scripts/imgsave.php';
)};
And PHP:
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {
$dataURL = $_POST["image"];
$parts = explode(',', $dataURL);
$data = $parts[1];
$data = base64_decode($data);
$fp = fopen('../images/test.png', 'w');
fwrite($fp, $data);
fclose($fp);
}
The problem is, that whatever I do, PHP saves empty file on my server. So I guess the dataURL is not send properly. What could be the issue here?
Your casing is incorrect:
The callback function creates dataUrl while your ajax call sends dataURL
BTW, it's good practice to extend your ajax call with .done and .fail callbacks ;)
Updated code:
$('#someButton').click(function(){
hiddenCanvas.toDataURL({
callback:function(dataUrl){
$.ajax({
type: "POST",
url: "scripts/imgsave.php",
data: {image: dataUrl}
});
}
});
window.location = 'scripts/imgsave.php';
)};
I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.