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);
}
Related
I have this php function which returns me a CSV file. This function needs the parameter $getid which I send through the url:
$getid = $_GET['id'];
$funcid = $_GET['funcid'];
if ($funcid == 'get_download') {
function get_download($dbmi, $getid) {
$stmt = $dbmi->prepare("CALL spStartDownload(?)");
$stmt->bind_param('i', $getid);
$stmt->execute();
$result = $stmt->get_result();
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
fputcsv($fp, $headers, ";");
while($row = $result->fetch_assoc()) {
fputcsv($fp, $row, ";");
}
}
$stmt->close();
echo $fp;
}
}
To send this parameter, I use this $.ajax() function:
function startDownload(id) {
setTimeout(function() {
showLoader('start...');
var funcid = "get_download";
var jqxhr = $.ajax({
type: 'GET',
url: 'functions/getdata.php',
data: {
funcid: funcid,
id: id
},
dataType: 'json'
}).done(function(myData) {
if (myData == null) {
showAlert();
} else {
}
hideLoader();
})
.fail(function() {showAlert();}); //When getJSON request fails
}, 0);
}
I'm a bit stuck here because the CSV file wont start downloading but when I type the url in the browser with the two parameters (funcid and id) it does work..
Any thoughts?
The issue I am having is that I cannot seem to USE the result passed back to the original JS file from the PHP file called from the request. This is the result and handler:
if(creds_verification() == true){
$.ajax({
url:"scripts/scripts.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {url: URL, user: USER, password: PASS},
success:function(result){
var verdict = result
if(verdict == "Yes"){
Call another external function
}else{
console.log(results.abc)
}
}
});
}
The console is constantly printing "Yes", aka the result of results.abc... why would this happen? It SHOULD be executing the next function...
Added Info
PHP script running shell command and echoing the result:
scripts.php
<?php
$URL = $_POST['url'];
$USER = $_POST['user'];
$PASSWORD = $_POST['password'];
echo json_encode(array("abc" => shell_exec("PATH.../phantomjs PATH/phantom/examples/test.js 2>&1 $URL $USER $PASSWORD")));
?>
And the JS file this is calling from the shell command:
test.js
var system = require('system')
var page = require('webpage').create()
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-1.11.0.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
var URL = system.args[1]
var USER = system.args[2]
var PASS = system.args[3]
var steps = [
function() {
page.open('http://'+URL+'/login.html')
},
function() {
page.evaluate(function(USER, PASS) {
document.querySelector('input[name="log"]').value = USER
document.querySelector('input[name="pwd"]').value = PASS
document.querySelector('form').submit()
}, USER, PASS)
},
function(){
var newURL = page.url
if(newURL == 'http://'+URL+'/user.html'){
console.log('Yes')
}else{
console.log('No?')
}
}
]
var stepindex = 0
var loading = false
setInterval(executeRequestsStepByStep, 5000)
function executeRequestsStepByStep(){
if (loading == false && steps[stepindex]) {
steps[stepindex]()
stepindex++
}
if (!steps[stepindex]) {
phantom.exit()
}
}
page.onLoadStarted = function() { loading = true }
page.onLoadFinished = function() { loading = false }
It's because the code you call on the server (this means the result of scripts/scripts.php) instead of returning 'Yes' as the result is putting the 'Yes' in the abc property of a returned object.
Change the php code to:
<?php
$URL = $_POST['url'];
$USER = $_POST['user'];
$PASSWORD = $_POST['password'];
$res = shell_exec("PATH.../phantomjs PATH/phantom/examples/test.js 2>&1 $URL $USER $PASSWORD");
echo json_encode($res == 'Yes' ? $res : array("abc"=>$res));
?>
Edit if the result of test.js is just "Yes" or "No" then change the PHP to
<?php
$URL = $_POST['url'];
$USER = $_POST['user'];
$PASSWORD = $_POST['password'];
$res = shell_exec("PATH.../phantomjs PATH/phantom/examples/test.js 2>&1 $URL $USER $PASSWORD");
echo json_encode(preg_replace("/[^A-Za-z]/", '', $res));
?>
and the javascript to
if(creds_verification() == true){
$.ajax({
url:"scripts/scripts.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {url: URL, user: USER, password: PASS},
success:function(result){
if(result == "Yes"){
Call another external function
}else{
console.log(result)
}
}
});
}
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.
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);
});
When I tried to used ajax to post data from javascript file to php file, there was nothing displayed on php file after using
$_POST['userinput']
Here is the javascript file:
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
userinput = places[0].name.toString(); // Get user input from search box
// Pass data to userinput.php via ajax
$.ajax({
url: 'userinput.php',
data: {userinput : userinput},
type: "POST",
success: function (result) {
alert(JSON.stringify(result));
}
});
});
php file:
if (isset($_POST)) {
$servername = "localhost";
$username = "XXXXXXX";
$password = "XXXXXXXXX";
$dbname = "CALIFORNIA";
$city = $_POST['userinput']; // Nothing is posted here
// Create connection
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, 1);
$sql = $conn->prepare("SELECT State FROM CITY as C WHERE C.City_name=$city");
$sql->execute();
$result = $sql->fetchAll();
$json = json_encode($result);
echo $json;
}
I was able to connect to the mysql database. However, there was no data posted from javascript file to php. I'm not sure what to do from this point. the value $city print out nothing. On the client side it printed out an empty object.
in your ajax function try setting dataType property
$.ajax({
url: 'userinput.php',
data: {'userinput' : 'userinput'},
type: "POST",
dataType: "text", // add this property
success: function (result) {
alert(JSON.stringify(result));
}
});