Issue on Posting Image to a PHP File - php

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".

Related

Corrupt pdf downloading when i am using MPDF with ajax call in codeigniter.I am using mPDF library

code at controller side is given below
try {
$this->load->library('m_pdf');
$querytype = "advance_search";
$showdata = [];
$pdfFilePath = utf8_decode("download_pdf.pdf");
ob_start();
$body= $this->load->view('result/pdf_generation', $this->common_advance_search($querytype),false); //here i am loading view for pdf
$this->m_pdf->pdf->WriteHTML($body);
$this->m_pdf->pdf->Output(FCPATH.$pdfFilePath,'F');// till here i can see the data in view
$result = ob_get_clean();
$response = array(
'op' => 'ok',
'file' => "data:application/pdf;base64,".base64_encode($result)
);
die(json_encode($response));
}
catch(\Mpdf\MpdfException $e) {
echo $e->getMessage();
}
Ajax Code
$.ajax({
url : "<?php echo base_url(); ?>"+scr,
method:"POST",
data:formData,
contentType: false,
cache: false,
processData:false,
dataType:'json'
}).done(function(data){ // here i am able to download the pdf in the browser
var $a = $("<a>");
$a.attr("href",data.file);
$("body").append($a);
$a.attr("download","file."+ext);
$a[0].click();
$a.remove();
});
result is given below
check result (screen shot added here)
with this code, it is giving me a currpted PDF file, i am able to get data and 'Export as pdf'. I have checked whether it is passing data from view, and yes it is doing so. But don't know what is the matter . I is printing everything outside it is working fine, Can anyone please let me know what should I do?

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';

How to use ajax to execute php function that will push a file to the browser?

I'm trying to write a method in a php class that will use ajax to execute a php function that will push a file back to the browser.
It seems like its trying to write the file to the modx log, getting a lot of binary garbage in there.
Here is the method:
public function pushDocuments($formdata){
$data = $formdata['formdata'];
$file = MODX_PROTECTED_STORAGE . $data['target'];
$file_name = basename($file);
if (file_exists($file)) {
header("Content-Disposition: attachment; filename=\"$file_name\"");
header("Content-Length: " . filesize($file));
header("Content-Type: application/octet-stream;");
readfile($file);
};
$output = array(
'status' => 'success',
'error_messages' => array(),
'success_messages' => array(),
);
$output = $this->modx->toJSON($output);
return $output;
}
and here is the jquery:
$('.btn-get-document').click(function(){
var target = $(this).attr('data-target');
var postdata = {"snippet":"DataSync", "function":"pushDocuments", "target": target}; // data object ~ not json!!
console.log('target = ' + target + postdata );
$.ajax({
type: "POST",
url: "processors/processor.ajax.generic/",
dataType : "json",
cache : false,
data: postdata, // posting object, not json
success: function(data){
if(data.status == 'success'){
console.log("SUCCESS status posting data");
}else if(data.status == 'error'){
console.log("error status posting data");
}
},
error: function(data){
console.log("FATAL: error posting data");
}
});
});
it's running through the scripts and giving a success in the console [because I am forcing success] but no file is prompted for download and the binary garbage shows up in the modx log
What am I doing wrong?
In order to download a file, you'd have to use JS to redirect to the file's location. You can't pull the file contents through AJAX and direct the browser to save those contents as a file.
You would need to structurally change your setup. For instance, your PHP script can verify the existence of the file to be downloaded, then send a link to JS in order to download the file. Something like this:
if ( file_exists( $file )) {
$success_message = array(
'file_url' => 'http://example.com/file/to/download.zip'
);
}
$output = array(
'status' => 'success',
'error_messages' => array(),
'success_messages' => $success_message
);
Then modify the "success" portion of your AJAX return like this:
success: function( data ) {
if ( data.status == 'success' ) {
location.href = data.success_messages.file_url;
} else if ( data.status == 'error' ) {
console.log( 'error status posting data' );
}
},
Since you're directing to a file, the browser window won't actually go anywhere, so long as the file's content-disposition is set to attachment. Typically this would happen if you directed to any file the browser didn't internally handle (like a ZIP file). If you want control over this so that it downloads all files (including things the browser may handle with plugins), you can direct to another PHP script that would send the appropriate headers and then send the file (similar to the way you're sending the headers and using readfile() in your example).
#sean-kimball,
You might want to extend MODX's class based processor instead:
https://github.com/modxcms/revolution/blob/master/core/model/modx/processors/browser/file/download.class.php
It does the download from any media source and also access checking if you want.
Its implementation on manager side is:
https://github.com/modxcms/revolution/blob/master/manager/assets/modext/widgets/system/modx.tree.directory.js#L553
Back to your case, these examples might bring you some ideas.
JS Example:
$.ajax({
type: "POST",
// read my note down below about connector file
url: "assets/components/mypackage/connectors/web.php",
dataType : "json",
cache : false,
data: {
action: 'mypath/to/processor/classfile'
}
success: function(data){
},
error: function(data){
console.log("FATAL: error posting data");
}
});
Processor example:
<?php
require_once MODX_CORE_PATH . 'model/modx/processors/browser/file/download.class.php';
class myDownloadProcessor extends modBrowserFileDownloadProcessor {
// override things in here
}
return 'myDownloadProcessor';
For this, I also suggest you to use MODX's index.php main file as the AJAX's connector so the $modx object in processor inherits the access permission as well.
http://www.virtudraft.com/blog/ajaxs-connector-file-using-modxs-main-index.php.html

passing base64string to php file using ajax and post

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");
}
});

javascript image upload via datauri and php base64 decode

I am trying to make an image upload where the JavaScript posts DataURI of an image via AJAX and the PHP receives it to decode it into an image.
The problem is, everything is working fine except that the end product is not an image file.
Please have a look at the following example code.
JavaScript:
dataString='encodedimg='+e.target.result.match(/,(.*)$/)[1]+'&type='+type;
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
data: dataString,
success: function(data){
//print success message
});
PHP:
$encodedimg = $_POST['encodedimg'];
file_put_contents('asdf.png', base64_decode($encodedimg));
There is no problem with $_POST['encodedimg'] as it produces the right image using online base64 converter. So I am assuming that there is a misuse with file_put_contents() or base64_decode().
Appreciate the help!
To read image on PHP i used a function like this
function rcd($data) {
$p = strpos($data, ',');
$d = base64_decode(substr($data, $p+1));
$rfn = md5(mt_rand(1,123123123));
file_put_contents($rfn, $d, LOCK_EX);
return $rfn;
}
Usage example:
$img_file_name = rcd($_POST['image_data']);
On JS part it is tricky (different browsers, etc). First of all You need to have the image data. Now You do not precise how this is sourced and the code example does not give a hint. We can assume some options
Simple You get dataString properly populated by whatever means neccesary, then Your example should basically work
imgdata = .... // any means of getting the data
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
image_data: imgdata,
success: function(data){
//print success message
});
Not so simple You have a Canvas object on the screen which was populated by any means and You want to send that data. Whatever above is true, however the way to get image data would be
var canv = document.getElementById('id_of_canvas');
imgdata = canv. toDataURL('image/jpeg', 0.88); // last arg is quality
However, as some browsers (mobiles) might not be so lucky to support this, you might want to find JPEGEncoder for JS and add it, along with the code below, to Your project.
var tdu = HTMLCanvasElement.prototype.toDataURL;
HTMLCanvasElement.prototype.toDataURL = function(type,param1)
{
var res = tdu.apply(this,arguments);
if(res.substr(0,11) != "data:image/")
{
var encoder = new JPEGEncoder();
return encoder.encode(this.getContext("2d").getImageData(0,0,this.width,this.height), (param1 ? param1*100 : 88));
}
else return res;
}
Hope this helps!
FOr #Marcin Gałczyński:
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
image_data: imgdata,
success: function(data){
//print success message
}
})
I think jQuery.ajax didnt have image_data jQuery.ajax

Categories