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);
}
});
Related
I want to generate a csv file with a dynamic filename which came from the values I got using an ajax jquery request. These values will be used as filename for my generated csv file. My program does not generate the csv file. What should I do for the csv file to be generated?
I am a newbie when it comes to php and especially AJAX and Jquery so I am still a bit confused on how an AJAX request works.
I'm using a free trial version of Sublime IDE and localhost for php. The program displays the contents of the csv file through an alert box but it doesn't generate a csv file.
This is my jquery ajax request file:
var selectedLanguage = $('#selectLanguage').val();
var length;
length = selectedLanguage.length;
for (var i = 0; i < length; i++)
{
var selectedLanguage = $('#selectLanguage').val();
$.ajax({
crossDomain: true,
async: false,
url: "downloadFile.php",
type: "GET",
data: {"seLang": selectedLanguage[i]},
success: function(data)
{
alert(data);
location.reload();
}
});
}
This is my downloadFile.php code:
<?php
$id="";
if(isset($_GET['seLang'])){
$id = $_GET['seLang'];
$filename = "File_".$id.".csv";
$f = fopen('php://memory', 'w');
//set headers for column
$fields = array('Content1', 'Content2', 'Content3','Content4');
fputcsv($f, $fields, ',');
fseek($f, 0);
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '";');
fpassthru($f);
}
else
{
echo "<script type='text/javascript'>alert('Empty');</script>";
}
?>
Edit 1:
Thank you Prvn and Sunday Johnson for trying to help. Although, I've found the actual problem. I've read from another post in this site that it is isn't possible to download the generated csv file using AJAX. What else can I do for me to download a csv file?
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$fields = array('Content1', 'Content2', 'Content3','Content4');
$fp = fopen('php://output', 'wb');
foreach ( $fields as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
Output
One comment about the Ajax code, why are you iterating over the value?
About the php code, use this instead:
<?php
$id="";
if(isset($_GET['seLang'])){
$id = $_GET['seLang'];
$filename = "File_".$id.".csv";
$f = fopen($filename, 'w');
//set headers for column
$fields = array('Content1', 'Content2', 'Content3','Content4');
fputcsv($f, $fields, ',');
fclose($f);
}
else
{
echo "<script type='text/javascript'>alert('Empty');</script>";
}
?>
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);
});
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));
?>
I have some files on my PHP server inside uploads folder. My problem is the following: I want to send a JSON asynchronous request from my client as to choose one of these files and create with this an image element as to display it in the browser.
JS code
var file_name="test.jpg";
$.ajax({
method:"POST",
dataType:"json",
url:"retrieve_photo.php",
data:{name:file_name},
success: function(data) {
var new_thumb = document.createElement("img");
document.getElementById('dragarea').appendChild(new_thumb);
...
}
})
PHP code (retrieve_photo.php):
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder="uploads";
$file_name=$_POST[name];
$files = glob($storeFolder.$ds.$file_name);
if ( false!==$files ) {
....
}
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($result);
?>
I do not know what to write as $result feeds data the right way. I 've tried
$result=readfile($storeFolder.$ds.$file_name);
but maybe not correctly.As to conclude I want to use data as to display an image to my browser.
Thank you
Maybe will be better do something like that?:
var image = new Image();
image.src = "blabla";
$(image).on('load', function(){
//do what you want
})
Why do you even use AJAX? Maybe i don't understand)
Since you don't use algorithm or functions in your PHP, you can do everything by Javascript / Jquery :
var img = $("<img />").attr('src', 'uploads/'+ file_name)
.on('load', function() {
if (!this.complete || typeof this.naturalWidth == "undefined") {
alert('Image not found');
} else {
$("#dragarea").append(img);
}
});
document.getElementByI('dragarea').appendChild(new_thumb);
Мaybe you mean? document.getElementById('dragarea').appendChild(new_thumb);
document.getElementById('dragarea').appendChild(new_thumb);
try this in your retrieve_photo.php
$filename = "test.jpg";
//Make sure $filename contains the appropriate path of the photo
$size = getimagesize($filename);
$file = $filename;
if ($size) {
header("Content-type:". $size['mime']);
header("Content-Length: " . filesize($file));
header("Content-Disposition: attachment; filename=$filename");
header('Content-Transfer-Encoding: base64');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Type: application/force-download");
readfile($file);
exit;
}
I'm trying to use Javascript to read stock data from yahoo finance at "http://table.finance.yahoo.com/table.csv?s=000001.sz", which returns a csv file and convert the data into json format as in http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=? to be used in highcharts.
I tried using $.ajax get and jquery.get but neither worked. Can somebody tell me how to read the data from the url and convert it into json? Thanks a lot.
This can be easily done with PHP.
<?php
file_put_contents("data.csv", fopen("http://table.finance.yahoo.com/table.csv?s=000001.sz", 'r'));
//reads the CSV file and save value into an associative array
function csv_to_array($filename = '', $delimiter = ',')
{
if (!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
if (!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$arr = csv_to_array('data.csv');
//<pre></pre> tags appear only to prevent white-space collapsing
//prints the associative array
echo "<pre>";
print_r($arr);
echo "</pre>";
//displays the the JSON
echo "<pre>";
echo json_encode($arr, JSON_PRETTY_PRINT);
echo "</pre>";
?>
Now depending on the format of JSON that it acceptable to Highcharts API, you are required to tweak how the array is encoded into JSON.
Also avoid using JSON_PRETTY_PRINT if the size of the incoming data is large.
I guess you are facing Cross Domain issue. Use jsonp calls for Cross Domain requests. Use something like this
$.ajax({
url : "http://xx.xx.xx.xx/xxx/xxx",
type: "GET",
dataType: "jsonp",
jsonp : "callback",
success: function(data) {alert("Success");},
error: function(data) { alert("Error"); }
});
});