Callback unique filename with jquery php - javascript

I am using html2canvas and Canvas2Image to create a png image from canvas and save it to the server with a unique filename.
I would like to know how to retrieve and show the unique filename after it gets generated.
jQuery
$(function() {
$("#convertcanvas").click(function() {
html2canvas($("#mycanvas"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
// Convert for sharing
var img = canvas.toDataURL("image/png",1.0);
$.ajax({
url:'save.php',
type:'POST',
data:{
data:img
}
});
PHP
<?php
$data = $_POST['data'];
$data = substr($data,strpos($data,",")+1);
$data = base64_decode($data);
$file = 'images/myfile'.md5(uniqid()).'.png';
file_put_contents($file, $data);
?>
Thanks in advance for any help.

You can get the filename by returning it in your PHP and catching it in the AJAX with a succes method.
PHP
<?php
$data = $_POST['data'];
$data = substr($data,strpos($data,",")+1);
$data = base64_decode($data);
$filename = 'myfile'.md5(uniqid()).'.png'; // <-- Added this because you probably don't want to return the image folder.
$path = 'images/'.$filename;
file_put_contents($path, $data);
echo $filename; // <-- echo your new filename!
?>
jQuery
$.ajax({
url:'save.php',
type:'POST',
data:{
data:img
},
success: function(data) {
alert(data); // <-- here is your filename
handleData(data);
}
});

You can simply give back the filename inside of an array and return it as JSON with json_encode.
PHP
<?php
$data = $_POST['data'];
$data = substr($data,strpos($data,",")+1);
$data = base64_decode($data);
$file = 'images/myfile'.md5(uniqid()).'.png';
file_put_contents($file, $data);
echo json_encode(array('filename' => $file));
?>
And in your script you can specify to expect json data by setting the 'dataType' property to "json". Then you can use the .done() function to do anything you want with the returned data, for example console logging it:
jQuery
var img = canvas.toDataURL("image/png",1.0);
$.ajax({
url:'save.php',
type:'POST',
dataType: 'json',
data:{
data:img
}
}).done(function(data){
console.log(data);
});

Related

Using an AJAX call to display base64 image data via PHP

I'm wanting to render an image using an AJAX call but I’m having trouble returning an image from the server as a base24 string via PHP.
In the renderImage function below the test image data 'R0lGODlhCw...' is displaying correctly but the image data coming from the AJAX call is not.
I want to use AJAX instead of just outputting the image file contents into the src attribute because I eventually want to add authorization headers to the PHP file.
I think I’m missing something in the PHP file and some headers in the ajax call?
PHP file: image.php
<?php
header("Access-Control-Allow-Origin: *");
$id = $_GET["id"];
$file = '../../upload/'.$id;
$type = pathinfo($file, PATHINFO_EXTENSION);
$data = file_get_contents($file);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
return $base64;
?>
JS
function renderImage(id) {
//return "R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==";
return $.ajax({
url: '[server URL]/image.php',
data:{"id":id},
type: 'GET',
});
};
$('.feedImage').each(async function() {
try {
const res = await renderImage($(this).data("id"));
$(this).attr("src","data:image/gif;base64," + res);
} catch(err) {
console.log("error"+err);
}
});
raw image obtained from How to display an image that we received through Ajax call?
First you should fix your php image rendering
<?php
header("Access-Control-Allow-Origin: *");
$id = $_GET["id"];
$file = '../../upload/'.$id;
$type = pathinfo($file, PATHINFO_EXTENSION);
$data = file_get_contents($file);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo json_encode(array('id' => $base64));
?>
Then your javascript, as you already defined the data image type there is no need to repeat it on the javascript.
function renderImage(id) {
//return "R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==";
return $.ajax({
url: '[server URL]/image.php',
data:{"id":id},
type: 'GET',
});
};
$('.feedImage').each(async function() {
try {
const res = await renderImage($(this).data("id"));
$(this).attr("src", res);
} catch(err) {
console.log("error"+err);
}
});

Sessions using AJAX

I have a website where I process signatures. I transfer them to a png and save them to my server using AJAX. I'm trying to save them in a folder with the username of them user using a variable in PHP. I would like to have this variable stored in the session however when I tried it did not work.
I have tried having the session running in both pages
The beginning of the file with the sig pad:
session_start();
$name = $_POST['name'];
$emp = $_POST['empid'];
$_SESSION["name"] = $name;
The submit function:
$(document).ready(function(e){
$(document).ready(function() {
$('#signArea').signaturePad({drawOnly:true, drawBezierCurves:true, lineTop:90});
});
$("#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,/, "");
//ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: { img_data:img_data },
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
});
session_start();
if(isset($_SESSION['name'])) {
$name = $_SESSION['name'];
$result = array();
$imagedata = base64_decode($_POST['img_data']);
$filename = 'signature';
//Location to where you want to created sign image
$file_name = './contracts'.$name.'/'.$filename.'.png';
file_put_contents($file_name,$imagedata);
$result['status'] = 1;
$result['file_name'] = $file_name;
echo json_encode($result);
}

Sending image file to php through ajax formData

The following is my code.I am unable to send the image file to the php page.I'm using formData and i'm not clear about the concept of it.How do i send it to php page and how do i retrieve The image in php page?
JAVASCRIPT CODE
function UpdateUserDetails() {
var title = $("#title1").val();
var store = $(".search-box").val();
var category= $("#category").val();
var descp=$("#descp1").val();
var url=$("#url1").val();
var id = $("#hidden_user_id").val();
var form = $('#image1')[0];
var formData = new FormData(form);
$.post("update.php", {
id: id,
title:title,
store:store,
category:category,
descp:descp,
data:formData,
url:url
},
function (data, status) {
$("#update_user_modal").modal("hide");
readRecords();
}
);
}
update.php
<?php
include("db_connection.php");
if(isset($_POST))
{
$id = $_POST['id'];
$title=$_POST['title'];
$desc=$_POST['descp'];
$pname=$_POST['store'];
$category=$_POST['category'];
$url=$_POST['url'];
$path = $_FILES['tmp_name'];
$name = $_FILES['name'];
$size = $_FILES['size'];
$type = $_FILES['type'];
$content = file_get_contents($path);
$content = base64_encode($content);
$sql1 = "update products set title='$title',url='$url',store='$pname', product_catagory='$category', image='$content',size='$size',type='$type',descp='$desc' where id=".$id."";
if(mysql_query($sql1))
{
echo"updated";
}
else
echo "Not Updated";
}
?>
Try this:
Jquery:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php:
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
It works for me.

Saving data into a text file sent as JSON with Ajax

I have currently a problem with my code. I would like to send JSON data with Ajax to a PHP script but it doesn't work. What does work is that the PHP script can be called by the Ajax code but it can't put the code into the .txt file. I have tried several things but I can't get it working. (I am trying to set the users array in the .txt file)
jQuery code:
var users = [];
$.ajax({
type: "POST",
url: hostURL + "sendto.php",
dataType: 'json',
data: { json: JSON.stringify(users) },
success: function (data) {
alert(data);
}
});
PHP Code:
<?php
$json = $_POST['json'];
$data = json_decode($json);
$file = fopen('test.txt','w+');
fwrite($file, $data);
fclose($file);
echo 'Success?';
?>
You must know that in PHP json_decode generates an Array that you can't write into an text file.
So only remove the json_decode command.
Since json_decode() function returns an array, you can use file_put_contents() that will save each array element on its own line
<?php
$json = $_POST['json'];
$data = json_decode($json, true);
file_put_contents('test.txt',implode("\n", $data));
?>

Return data back to ajax call in jquery

I have a php code (no functions, just direct code) which queries a data base stores values
in an array and returns the array
<?php
//Query the database and fetch some results
$array["min_date"] = $arr['min(date)'];
$array["max_date"] = $arr['max(date)'];
$array['query'] = $query;
echo $arr['min(date)'].'</br>';
echo $arr['max(date)'];
return $array;
?>
this is my jquery ajax call
function date(){
$temp = $('select[name=people_name]').val();
$name = $temp;
$table = 'myTablename';
$url = "/myurl/php/get_date.php?name="+$name+"&table="+$table;
$.ajax({
type: "POST",
url: $url,
success: function(data) {
document.getElementById("from_date").value = data['min_date'];
document.getElementById("to_date").value = data['max_date'];
}
});
}
when I echo the php variables I do get the data which I want. but logging the jquery variables the give me result as undefined.
maybe the php return data is not fetches by ajax success(data)? or do I need to have a function in my php code? how do I fetch returned array in my jquery?
Thanks!
Try encoding the array in php side with json_encode().
In your PHP
//Query the database and fetch some results
$array["min_date"] = $arr['min(date)'];
$array["max_date"] = $arr['max(date)'];
$array['query'] = $query;
echo json_encode($array); //add this
In ajax call
function date(){
$temp = $('select[name=people_name]').val();
$name = $temp;
$table = 'myTablename';
$url = "/myurl/php/get_date.php?name="+$name+"&table="+$table;
$.ajax({
type: "POST",
dataType:'json', //add dataType
url: $url,
success: function(data) {
document.getElementById("from_date").value = data.min_date;
document.getElementById("to_date").value = data.max_date;
}
});
}

Categories

Resources