Javascript dataURL POST to PHP not working - javascript

I'm trying to post dataURL over to php but with no succsess.
My .js file is as follow.
var dataURL = signaturePad.toDataURL();
alert(dataURL);
$.ajax({
type: "POST",
url: "test.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
alert(o);
});
alert(dataURL) output is as follow;
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhkAAADZCAYAAACNbSIWAAAeW.....
test.php
<?php
if($_POST['imgBase64']) {
$img = $_POST['imgBase64'];
}
else{
$img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhkAAADZCAYAAACNbSIWAAAeW.....";
}
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//saving
$timestamp = date('YmdHis');
$fileName = ''.$timestamp.'.png';
echo"$fileData";
file_put_contents($fileName, $fileData);
?>
In my php file I have entered the value of my alert for testing purposes. Now my php page is working 100% due to the test and passing no value from my .js function. but with the correct value it's not even posting to my php page, only when I remove all not standard characters from the dataURL then it post but obvious with corrupt data.
To avoid further confusion the following code works 100%, the .js and the php. where var dataURL = signaturePad.toDataURL(); is passed to the function
function postData(data) {
alert(data);
var desired = data.replace(/[^\w\s]/gi, '');
$.ajax({
type: "POST",
url: "test.php",
data: {
imgBase64: desired
}
}).done(function(o) {
console.log('saved');
alert(o);
});
}
So the problem is the .js will not post with the given dataUrl due to special characters, but I cant remove them.. I even tried var desired = encodeURIComponent(data); witch I can at least decode on the php page but this also does not want to post.

data: {
imgBase64: data
//send key is imgBase64 and data value is undefined in given scope
//replace data with dataURL
}
And in php file change this $_POST['image'] to $_POST['imgBase64']

Thanks for the replies..
I ended up creating a blob first and posting the blob.
function dataURLToBlob(dataURL) {
var parts = dataURL.split(';base64,');
var contentType = parts[0].split(":")[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
$.post("test2.php",
{
name: uInt8Array
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
}

Related

No data qrcode image pass to URL after Ajax function

I want to pass data via url using ajax, the result is that no data is captured by the post method.
(function() {
var qr = new QRious({
element: document.getElementById('qr'),
size: 200,
value: 'https://github.com/ddsfdf'
});
var img = qr.toDataURL('image/jpeg');
var img_data = img.replace(/^data:image\/(png|jpg);base64,/, "");
$.ajax({
'type': 'post',
'url': '<?php echo base_url('dasboard/qrcode'); ?>',
data: {
'img': img_data
},
success: function(response) {
}
});
})();
and this is the code in the controller:
$imagedata = base64_decode($_POST['img']);
$filename = $id;
$file_name = './saveimageQR/' . $filename . '.png';
file_put_contents($file_name, $imagedata);
i get result Undefined index:img which means no data sent,please help me Thank You.

Heic to jpg conversion using libheif

I am trying to convert .HEIC image to .JPG using libheif.
libheif converts image on client side browser window only. So in order to save the image i converted image to base64 and then performed ajax to save the image using file_put_contents.
this.canvas.toBlob(function(blob) {
var extension = FILE_EXTENSIONS[blob.type] || ".bin";
var basename = this.filename.replace(/\.[^/.]+$/, "");
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, basename + extension);
return;
}
var readers = new FileReader();
var base64image;
readers.readAsDataURL(blob);
readers.onload = function () {
var base64image = readers.result; // data <-- in this var you have the file data in Base64 format
// console.log(base64image);
// call ajax
var formData = new FormData();
formData.append('filename', basename);
formData.append('avatar', readers.result);
$.ajax('upload.php', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
},
error: function () {
}
});
};
return;
// this.downloads.appendChild(dlink);
// dlink.click();
// URL.revokeObjectURL(url);
}.bind(this), format);
When i convert a single image then it works fine. But if i try to convert in loop it does not works.
Before completing js conversion, my php loop runs (I think this is the issue) So i tried php function sleep() and js set timeout(), But unfortunately none worked.
(function() {
var demo = new HeifDemo(libheif);
<?php $img_array = array('demo/1.heic', 'demo/2.heic', 'demo/3.heic');
foreach ($img_array as $img) : ?>
function saveImage(subject, callback) {
demo.loadUrl(subject);
callback();
}
saveImage('<?php echo $img; ?>', function() {
// demo.saveImage();
setTimeout( function(){
demo.saveImage();
}, 2500 );
});
//});
<?php sleep(4); endforeach; ?> }).call();

Ajax code in php and javascript regarding an image file

I am trying to save image file through signature pad. I want the name of the file to be an element from my div. Which changes accordingly. Here is my code. It is saving the image but the filename is blank(.png).
Javascript:
$("#btnSaveSign").click(function(e){
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data = canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
var p = document.getElementById('my_class').innerHtml;
//ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: [{ img_data:img_data, p:p}],
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
save_sign.php:
<?php
$result = array();
$imagedata = base64_decode($_POST['img_data']);
$filename = $_POST['p'];
//Location to where you want to created sign image
$file_name = './doc_signs/'.$filename.'.png';
file_put_contents($file_name,$imagedata);
$result['status'] = 1;
$result['file_name'] = $file_name;
echo json_encode($result);
?>
Replace with your assignment with var p = document.getElementById('my_class').value;
Due to onrendered function is a callback, it may not get the document.getElementById('my_class').innerHtml properly. Please get echo out the $_POST['p'] to make sure proper filename is sent to PHP side.
get document.getElementById('my_class').innerHtml before call html2canvas function.
$("#btnSaveSign").click(function(e){
var p = document.getElementById('my_class').innerText;
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data = canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
// ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: [{ img_data:img_data, p:p}],
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
$("#btnSaveSign").click(function(e){
var p = document.getElementById('my_class').innerText;
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data = canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
// ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: [{ img_data:img_data, p:document.getElementById('my_class').innerText}],
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});

How to reload a img attr "src" after ajax call without knowing the file name from the image tag?

I have this html:
<div class="d-inline-flex">
<img id="reloadIMG" class="p-3 mt-5 imgP" onDragStart="return false" <?php echo htmlentities($avatar, \ENT_QUOTES, 'UTF-8', false); ?>>
<input type="file" id="uploadAvatar" name="uploadedAvatar">
</div>
the value of $avatar:
$pathFolderAvatar = 'user/'.$folder.'/avatar/*';
$imgUserPastaAvatar = glob($pathFolderAvatar)[0] ?? NULL;
if(file_exists($imgUserPastaAvatar)){
$avatar = 'src='.$siteURL.'/'.$imgUserPastaAvatar;
}else{
$avatar = 'src='.$siteURL.'/img/avatar/'.$imgPF.'.jpg';
}
and the script to send a ajax call to my file that process the file upload request:
$(function () {
var form;
$('#uploadAvatar').change(function (event) {
form = new FormData();
form.append('uploadedAvatar', event.target.files[0]);
});
$("#uploadAvatar").change(function() {
$("#loadingIMG").show();
var imgEditATTR = $("div.imgP").next().attr("src");
var imgEdit = $("div.imgP").next();
$.ajax({
url: 'http://example/test/profileForm.php',
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime());
}
});
});
});
i tried to force the browser to reload the img on success ajax call $(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime()); but the selector from the var imgEdit and imgEditATTR is not working:
console.log(imgEdit); result: w.fn.init [prevObject: w.fn.init(0)]
console.log(imgEdit); result: undefined;
Why is it happening, and how to fix?
I know that there's a bunch of questions about reload img, but on these questions there's not a method to reload a image without knowing the file name. I checked so many questions and this is what the answears say:
d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
On my case i don't know the file name, because it's generated randomly on profileForm.php with mt_rand():
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
//example of the result: 9081341_1546973622.jpg
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
You can return file name in response to your AJAX request and use it in success block to update src attribute of img tag
So your profileForm.php will look something like
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000).'_'.time();
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'.'.$extension;
//example of the result: 9081341_1546973622.jpg
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
echo $newname // you can also send a JSON object here
// this can be either echo or return depending on how you call the function
and your AJAX code will look like
$.ajax({
url: 'http://example/test/profileForm.php',
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', data);
}
});
Let profileForm.php return the generated filename:
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
echo json_encode(['filename' => $folderPFFetchFILE]);
Then in the callback of your POST request:
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', data.filename);
}

pdf file upload ajax html

var file = $('#image').prop('files')[0];
var filename = $('#af_rpta_propertyland_filename').val();
var form_data = new FormData();
form_data.append('file', file);
alert(form_data);
$.ajax({
type: 'POST',
url: '../include/upload.php',
//dataType: "json",
data: {
file: form_data,
filename: filename
},
success: function(data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
console.log("file " + i + ": " + data[i].file);
}
},
error: function(data) {
alert('No Record Found: ' + data);
}
});
<input id="image" name="image" type="file" />
This how i upload my pdf file using ajax in my php code i do it like this
$file = mysql_real_escape_string($_POST['file']);
$filename = mysql_real_escape_string($_POST['filename']);
if (isset($_FILES['file']) && $_FILES['file']['size'] > 0) {
$tmpName = $_FILES['file']['tmp_name'];
$filetype = $_FILES['file']['type'];
$fp = fopen($tmpName, 'rb'); // read binary
$upload[] = array('filename' => $filename,'file' => $fp);
}
echo json_encode($upload, JSON_UNESCAPED_UNICODE);
From my input(type file) how can i place the value(the pdf file) in to data(in ajax) and from data(ajax) how can i pass it to php file so that i can check if the $_files is not empty
Try creating a json object from files[0] properties , converting file to base64 string
js
$("#image").on("change", function(e) {
var name = $("#af_rpta_propertyland_filename").val()
, file = e.target.files[0]
, filename = name.length > 1 ? name + ".pdf" : file.name
, filetype = file.type
, filesize = file.size
, data = {
"filename":filename,
"filetype":filetype,
"filesize":filesize
}
, reader = new FileReader();
reader.onload = function(e) {
data.file_base64 = e.target.result.split(/,/)[1];
$.post("fileupload.php", {file:data}, "json")
.then(function(data) {
// parse `json` string `data`
var filedata = JSON.parse(data)
// do stuff with `data` (`file`) object
, results = $("<a />", {
"href": "data:" + filedata.filetype
+ ";base64," + filedata.file_base64,
"download": filedata.filename,
"target": "_blank",
"text": filedata.filename
});
$("body").append("<br>download:", results[0]);
}, function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
})
};
reader.readAsDataURL(file)
});
php
<?php
if (isset($_POST["file"])) {
// do php stuff
// call `json_encode` on `file` object
$file = json_encode($_POST["file"]);
// return `file` as `json` string
echo $file;
};
jsfiddle http://jsfiddle.net/guest271314/LL95z474/
Use jQuery version "jquery-1.10.2.min.js"
Use this AJAX
$.ajax({
url: "YourPage.php",
type: "POST",
data: new FormData('YourFormId'),
contentType: false,
processData:false,
success: function(data)
{
// Do your Stuff
}
});
At PHP page just simply use this line
$name = $_FILES['file']['name'];
In this code i have used two new events
contentType
processData
This is necessary to use these to upload and access all data in AJAX.
Hope this will help you.

Categories

Resources