passing base64string to php file using ajax and post - php

Using mobile apllication here, I am sending image encoded data to php file using post method and getting the image url from the php file. The problem here is, I am not getting proper image while am sending string using ajax. When I place the image data manually, I am able to view the image, but when sending the image data using ajax call, unable to view the image.
<?php
//$image = $_POST['uploadedfile'];//not working if an ajax call is made what is the issue here
$image ="base64 string of an image here";//working if i place base 64 string here
$binary = base64_decode($image);
$fileName = time() . ".jpeg";
file_put_contents('images/' . $fileName, $binary);
if (file_exists('images/' . $fileName)) {
$myjson12 = "[";
$myjson12.='{';
$myjson12.='"Certificate":"http://domain/demo/images/'.$fileName.'"';
$myjson12.='}';
$myjson12.="]";
echo "$myjson12";
} else {
echo 'FAILURE';
}
?>
When I am accessing the file url and sending the parameter value the output is coming as url is too long: www.domain.com/getdata.php?uploadedfile=base64stringvalue;
here is my ajax call
$.ajax({
type: "POST",
url: "www.domain.com/getdata.php",
data: { "uploadedfile": c.toDataURL("image/jpeg") },
// dataType: "json",
success: function (response) {
console.log(response + "Sri");
$("#loadImg").hide();
alert("Success");
},
error: function (data) {
$("#loadImg").hide();
alert("Connection Failed");
}
});

Related

Receive JSON response from AJAX POST request?

I'm setting up a system for users to upload profile pictures to the server. These profile pictures are cropped with Croppie, then sent with a POST request for processing to a PHP file.
This PHP file receives a response from the server if the image was accepted, or if there was an error.
I'm having difficulty passing this JSON response back to an AJAX variable, so I can show it to end-users.
I've set up a with the ID of "json" where the response should be shown. However, all that is being displayed is 'undefined'.
When displaying the 'response' variable without .msg, it displays the image URI - so it doesn't appear to be taking the requests made in the PHP script.
Here's what I've tried:
AJAX
$('.crop_image').on('click', function(ev) {
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response) {
$.ajax({
type: 'POST',
url: "core/account-mechanisms/push-profile-test.php?action=upload",
data: {
"image": response
},
});
$("#json").html('<div style="margin-top:15px;" class="alert alert-success">'
+ response.msg + '</div>');
})
});
PHP (start of script)
# Mechanism to upload image
if (isset($_POST['image'])) { # Check if image data is being sent by POST
$c_finalCheck = true;
$cropped_image = $_POST['image']; # Assign cropped_image from data received
$image_array_1 = explode(";", $cropped_image); # Create image with correct encoding
$image_array_2 = explode(",", $image_array_1[1]);
$cropped_image = base64_decode($image_array_2[1]);
$c_imgValid = getimagesize($c_fileCheck); # Set result of image validity and size check
if ($c_fileCheck == false) { # Run image validity check with response
$response['msg'] = 'Sorry, your image isn\'t valid. Please try again.';
$c_finalCheck = false;
header("Content-Type:application/json");
echo json_encode($response);
}
you are sending the Ajax Post to your Server, but you are not using the Ajax response. Instead you are displaying the response of your croppie call.
You need to do something like this:
$('.crop_image').on('click', function(ev) {
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response) {
$.ajax({
type: 'POST',
url: "core/account-mechanisms/push-profile-test.php?action=upload",
data: {
"image": response
},
}).done(function(data) {
$("#json").html('<div style="margin-top:15px;" class="alert alert-success">' + response + '</div>');
});
})
});
I did not try it but it should give you the right direction.
Here the jquery Api reference: Ajax

How can I create/save a file from BLOB in php?

What I did so far:
Okay, so i create a blob file (wav content) and it is stored under blob:http://localhost/cf6fefdc-352e-4cec-aef8-03af6d0d0ef6.
When i put this URL into my browser, it plays the file.
What i need to do
I want to convert the blob into an actual file, that i want to store on my webserver.
I'm handing the blob object over to a php file via AJAX
$.ajax ({
type: "POST",
url:"path/to/my/file.php",
data: {thefile : blob} ,
success: function(text) {
console.log(text);
},
error:function(){
console.log("Error")
}
});
That works. If I print_r the variable it returns [object Blob]
My PHP
<?php
$file = $_POST['thefile'];
print_r($file);
Can anyone tell me how I can convert and save the file to my server from there on?
In your file.php add this code
$filePath = 'uploads/' . $_POST['thefile'];
$tempName = $_FILES['thefile']['tmp_name'];
if (!move_uploaded_file($tempName, $filePath)) {
echo 'Problem saving file: '.$tempName;
die();
}
// success report
echo 'success';

Grabbing a php base64 image from angularJS

I'm trying to grab a 64base encoded string in php from angularJS and I'm not quite sure what I'm doing wrong. I've encoded an image that was written to server by the makegray.exe that php runs. Now I'm trying to grab that image and give it back to the angularJS that then displays it for the user. This seems like such a simple problem but I'm stumped as to how to do this.
$scope.MakeGray_Button = function(){
if ($scope.imageUrl) {
var MakeGray_Form = new FormData();
MakeGray_Form.append("FileName", $scope.imageUrl);
$http({
method : "POST",
url : "../opencv/MakeGray/MakeGray.php",
data : MakeGray_Form,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).
success(function(){
// some magic code here that grabs the $base64 variable from php
})
.error(function(){});
}
else{
alert("Please upload an image");
}
}
php
<?php
$imgname = $_POST["FileName"];
$inputDir = "../../uploads/" . $imgname;
$outputDir = "../../processed/" . $imgname;
$MakeGray = "./makegray " . $inputDir . " " . $outputDir;
$runExec = exec($MakeGray, $out);
$type = pathinfo($outputDir, PATHINFO_EXTENSION);
$data = file_get_contents($outputDir);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo "$base64";
?>
$scope.MakeGray_Button = function(){
if ($scope.imageUrl) {
var MakeGray_Form = new FormData();
MakeGray_Form.append("FileName", $scope.imageUrl);
$http({
method : "POST",
url : "../opencv/MakeGray/MakeGray.php",
data : MakeGray_Form,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function(response){
//response object should hold your base64 image data.
//you can change src of an img tag with ng-src and let the browser render your image.
},function(response){});
}
else{
alert("Please upload an image");
}
}
First of all use .then() in place of your deprecated functions .success() and .error()
then also capture response as in above code.
you can render the base64 image easily by having it as src of an img tag. ng-src should help for that.
if you want the image as string, you should check response object instead.
Ok I got it to work...
$scope.MakeGray_Button = function(){
if ($scope.imageUrl) {
var MakeGray_Form = new FormData();
MakeGray_Form.append("FileName", $scope.imageUrl);
$http({
method : "POST",
url : "../opencv/MakeGray/MakeGray.php",
data : MakeGray_Form,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).
success(function(data){
$scope.data = data;
base64 = data;
$("#img2").prop("src", base64);
})
.error(function(){});
}
else{
alert("Please upload an image");
}
}
Hope this helps anyone else trying to display an image to JS from php using base64 encoded strings!

Issue on Posting Image to a PHP File

I am trying to capture a highcharts chart and POST it to a PHP file
(result.php). I am able to capture image right now but I do not know how to POST captured image to another file. so far I have this code which is returning a PNG image
function postChart(chart) {
var obj = {},chart;
obj.svg = chart.getSVG();
obj.type = 'image/png';
obj.async = true;
exportUrl = 'http://export.highcharts.com/';
$.ajax({
type: "POST",
url: exportUrl,
data: obj,
cache:false,
async:true,
crossDomain:true,
success: function (data) {
// How to Send Image to result.php
},
error: function(data) {
}
});
}
and this result.php file as:
<?php
$content = $_POST['Not Sure What!'];
echo $content;
Now can you please let me know what can I put in
success: function (data) {
// How to Send Result to another Page
},
to post the image to result.php and how should I modify the result.php. Thanks
You can just use the highchart's exportChart API Like
function postChart(chart) {
chart.exportChart({
url : 'path/to/result.php',
type: 'image/png',
filename: 'my-chart'
});
}
Then from result.php you will be able to access the $_POST variable. which will contain following array, where $_POST['svg'] is the image in svg format.
array (
'filename' => 'my-chart',
'type' => 'image/png',
'width' => '0',
'scale' => '2',
'svg' => '',
)
You can then use the highchart's server side script to convert the image from svg to your desired format.
If you do not like to use java library for the conversion, you can also try this
Happy Coding!!
This works only if your php-script is somewhere on http://export.highcharts.com/
(Because you set the crossDomain property to true)
In your ajax method:
Change:
data: obj,
TO:
data: {
objName: obj,
}
Then in the result.php:
<?php
var_dump($_FILES['objName']);
// If you're interested, what else is inside $_FILES
var_dump($_FILES);
Not entirely sure what you're asking. This may be of some help though.
When working with files on upload use $_FILES. Its exactly like $_POST but for files.
Theres a selection of variables you can gather from the file using $_FILES.
<?
$tempname = $_FILES['file']['tmp_name'];
$filetype = $_FILES["file"]["type"];
$filesize = $_FILES['file']['size'];
?>
In the case above this references the file with a name of "file".

AJAX sending a base64 image to an external server

I'm trying to send a base64 image generated on one server and sent to a PHP file on another. So far all I'm getting cross origin errors on the client side and the server with the PHP file doesn't seem to receiving anything.
Here's the code:
Server 1 JS :
function shareDesign() {
$('#twitter').on('click', function() {
//console.log('?image='+encodeURIComponent(canvasExport)+'&designName=test')
$.ajax({
type: 'POST',
url: 'http://mysite.com/share_page.php',
dataType: 'text',
data: {
image : canvasExport ,
designName:'test'
} ,
success: function(data) {
console.log(data);
}
})
})
}
Server 2 PHP:
$image = $_POST['image'];
$designName = $_POST['designName'];
$sHTML_Header = "<html><head><title>SHare design test</title></head><body>";
$sHTML_Content = '<div id="test"><img src="'.$image.'"/> This design is called : '.$designName.'</div>' ;
$sHTML_Footer = "</body></html>";
echo "parseResponse({'status' :'success'})";
Addition:
I need this to work on mobile, is this possible? Also I do not have any server control on the JS server it's on adobe business catalyst.

Categories