Save chart image with open flash chart2 - javascript

I am using Open Flash Chart 2 to create some graphs. I want to be able to save an image of the graph, which OFC2 supplies some methods to accomplish this. I used the example on the OFC2 site to directly display the raw image data on the page, but that does not work in IE6, which most of our users are using (I know, I know).
I switched to using the OFC2 method, post_image to post the raw image data to the server. I use a Perl script to receive the image data, save it to a file, and I can view the image. The unfortunate part about using the post_image method is that ActionScript throws an error when saving the image:
Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
Which apparently is a bug in Adobe - see this page. Because of this error, the post_image method does not complete successfully, so the javascript callback won't ever fire - I basically don't have a way to tell if the image was saved successfully.
So, I thought I would use the get_img_binary method of OFC2 to get the binary data of the image, and use jQuery to post the binary data to my Perl script.
I cannot figure out how to send the binary data correctly, or how to let my Perl script receive the binary data correctly, or both.
Here is my jQuery function:
var chartObj = $("#chart_object").get(0);
$.ajax({
type: "POST",
url: 'download_image.pl',
//contentType: 'application/octet-stream',
contentType: 'image/png',
//processData: false,
//data: { imgData: chartObj.get_img_binary() },
data: chartObj.get_img_binary(),
dataType: "text",
success: function(data) {
console.log( data );
}
});
You can see from some of my commented out lines that I have tried various contentTypes and other settings of the Ajax call.
The Ajax call is sending some data, but it doesn't appear to be binary. I think it is a base64 representation of the binary data.
Does anyone have any ideas on how to send binary data from javascript to the server?
The Perl script I have works fine for the post_image method, so I don't think the problem is there?
Thanks in advance!

I seem to have stumbled onto the solution.
Here is my ajax call:
var chartObj = $("#chart_object").get(0);
$.ajax({
type: "POST",
url: 'download_image.pl',
contentType: 'application/octet-stream',
processData: false,
data: imgData,
dataType: "text",
success: function(data) {
console.log( data );
}
});
And here is my Perl snippet to process/save the image:
use CGI qw(:standard);
use MIME::Base64;
...
my $img64 = param('POSTDATA');
my $img = decode_base64( $img64 );
...
#then print $img out to a file in binary mode
I had to decode the base64 representation of the PNG file, and then save it to a file.

i've got trouble too with using IE6 and OFC2 for saving image... So here are the scripts i use (javascript + PHP)
i know it's not very beautifull but jQuery doesn't want to work in a popup created via window.open('') on my IE6 so i decided to use a "old school method" to get it...
// javascript in the page displaying the flash chart
OFC = {};
OFC.jquery = {
name: "jQuery",
image: function(src) { return '<img src="data:image/png;base64,' + $('#'+src)[0].get_img_binary() + '" \/>'},
popup: function(src) {
var img_tag = OFC.jquery.image(src);
var img_win = window.open('', 'imagesave');
img_win.document.write('<html><head><title>imagesave<\/title><\/head><body>'+ img_tag + '<\/body><\/html>');
img_win.document.close();
},
popupie: function(src) {
var img_data = "image/png;base64,"+$("#"+src)[0].get_img_binary();
var img_win = window.open('', 'imagesave');
with(img_win.document) {
write('<html>');
write('<head>');
write('<title>imagesave<\/title>');
write('<\/head>');
write('<body onload="document.forms[0].submit()">');
write('<form action="\/ofc\/base64post.php" method="post">');
write('<input type="hidden" name="d" id="data" value="'+img_data+'" \/>');
write('<\/form>');
write('<div><img src="\/ofc\/ajax-loader.gif" border="0" alt="" \/><\/div>');
write('<div style="font-family: Verdana;">Please wait<br \/>After you can save the image<\/div>');
write('<\/body>');
write('<\/html>');
}
img_win.document.close();
}
}
function save_image() { // this function is automatically called
if ($.browser.msie)
OFC.jquery.popupie("my_chart"); // only for IE navigators
else
OFC.jquery.popup("my_chart"); // for the others
}
so, when we use the save_image() function (which is automaticaly called when you right clic dans select "Save Image Locally" on the flahs chart)
the image of the chart is tranfered to the popup and the data (base64 binary image) are posted to a php script /ofc/base64post.php that rander the picture :
<?php
// base64post.php
$data = split(';', $_POST['d']);
$type = $data[0];
$data64 = split(',', $data[1]);
$pic = base64_decode($data64[1]);
header("Content-type: $type");
echo $pic;
?>
hope that help someone !

Related

Newlines in textarea not interpreted in text from database

I've got text that is 'ajaxed' in a textarea which is inside an iFrame (the source is from the same website).
If I set the content directly as an argument of one of the functions I tried it works fine and newlines get interpreted, but not when using the variable holding the data coming from the MySQL database.
I've tried multiple ways as I've seen in a few posts on stack but nothing works.
let content = $('#myFrame').contents(); // Get the content of the iFrame
let description = response.description; // Ajax data : text
content.find('#description').val('foo\r\nbar'); // Works
content.find('#description').html('foo\r\nbar'); // Works
content.find('#description').text('foo\r\nbar'); // Works
content.find('#description').val(description); // Doesn't work
content.find('#description').val(String(description)); // Doesn't work
content.find('#description').html(description); // Doesn't work
content.find('#description').html(String(description)); // Doesn't work
content.find('#description').text(description); // Doesn't work
As per request I'm adding more information however I can't put all the HTML, there's a lot of stuff.
The table settings in MySQL for that particular row :
Name : description
Type : text
Collation : utf8_general_ci
A php script uses mysqli to retrieve the data :
$description = $row['description'];
$arrayAr['description'] = $description;
Then sends the data to jquery as a JSON :
echo json_encode($arrayAr);
The ajax part with jQuery :
function ajaxStuff(link, num) {
$.ajax ({
url: link,
type: "POST",
data : {id: num},
dataType: "json",
cache: false,
success: function(response) {
let content = $('#myFrame').contents();
// the rest of this code is in the snippet above
}
The HTML, the actual page and the page called with the iFrame both have UTF-8 charset :
<iframe src='../forms/form2.php'
id='myFrame'
frameborder='0'
width=''
height='800'
scrolling=''
></iframe>";

Ajax doesn't get to success function. Always error function. It fails to post data to another file

Please be patient. This is my first post as far as I remember.
This is a part of my calendar.js script. I'm trying to POST data that I fetch from modal window in index.php to sql.php.
function saveModal() { /*JQuery*/
var current_date_range = $(".modal-select#daterange").val();
var current_room_number = $("#mod-current-room-number").val();
var current_room_state = $("#mod-current-room-state").val();
var myData = {"post_date_range": current_date_range, "post_room_number": current_room_number, "post_room_state": current_room_state};
var myJSON = JSON.stringify(myData);
$.ajax({
type: "POST",
url: "sql.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
data: myJSON,
beforeSend: function() {
$("#ajax").html("<div class='loading'><img src='/images/loader.gif' alt='Loading...' /></div>");
},
success: function(result){
$("#ajax").empty();
$("#ajax").html(result);
$("#ajax").fadeIn("slow");
window.location.reload(true);
},
error: function(){
alert(myJSON);
$("#ajax").html("<p class='error'> <strong>Oops!</strong> Try that again in a few moments.</p>");
}
})
}
I get the data just fine (as you can see I have checked in the error: function() with alert(myJSON);). It looks like this: {"post_date_range":"12/19/2018 - 12/28/2018","post_room_number":"118","post_room_state":"3"}. Nevermind that the daterangepicker.js returns dates in the hideous MM/DD/YYYY format, which I would very much like to change to YYYY-MM-DD. The real problem is, the code never gets to success: function().
Now my sql.php is in the same folder as calendar.js and index.php.
In sql.php I try to retrieve those values with:
$currentDateRange = $_REQUEST['post_date_range'];
$currentRoomNumber = intval($_REQUEST['post_room_number']);
$currentRoomState = intval($_REQUEST['post_room_state']);
I have checked many other SO Q&As and none have helped me solve my problem. I don't see any spelling errors. It's not disobeying same origin policy rule. I don't want to use jQuery $.post function. Anyone sees the obvious solution?
You want to send array in post rather than the string so directly send myData to get array value in your PHP file rather converting to JSON string It would work with your current PHP file as you require.
You should specify a POST key for the JSON data string you are sending:
var myJSON = JSON.stringify(myData);
(...)
$.ajax({
(...)
data: 'data=' + myJSON,
You need to parse (decode) this string in your PHP file to be able to use it as an array/object again:
$data = json_decode($_REQUEST['data']);
$currentDateRange = $data['post_date_range'];
$currentRoomNumber = intval($data['post_room_number']);
$currentRoomState = intval($data['post_room_state']);
Also, dataType in jQuery.ajax function is specified as "The type of data that you're expecting back from the server." according to jQuery documentation. As far as I can tell from your code, you might rather expect something else as your response, so try excluding this line.
I am sorry to have burdened you all. It's my third week programming so my lack of knowledge is at fault.
I did not know how dataflow works between AJAX and PHP in the URL...
While I was searching for other errors, I printed or echoed out many different things. The PHP file should echo only 1 thing, although it can be an array with multiple values.
Like this for example:
$return_arr = array("sql"=>$sql1, "result"=>$result, "out"=>$out);
echo json_encode($return_arr);
I appologize again.

jQuery how to return value without encoding it?

I have a problem with encoding/decoding some text.
On my page I have a picture:
<img id ="pcs" src="xxx.jpg" game="Hellblade: Senua’s Sacrifice ">
Then use ajax to send data to php server:
$('#pcs').click(function(){
if($(this).attr('src') == "xxx.jpg" ) {
$(this).fadeOut(100, function() {
var cookie = "dummy";
var game = $(this).attr('game');
$.ajax({
url: "http://example/notif_games.php",
type: "POST",
data: ({'cook_':'cookie', 'game_': game}),
});
The problem is the data are somehow encoded and recieved as: Hellblade: Senua’s Sacrifice
Instead, I need it to be recieved as: Hellblade: Senua’s Sacrifice
Even where I try
var game = $(this).attr('game');
alert(game);
it returns the 'encoded' value.
It's needed with the ’ part because I then put it in DB and compare it with another tables where the value is with the ’.
This is a browser issue and not a jquery one. Your browser is rendering the text already before jquery touches it. You need to decode it on the server side when you ajax it up.
With php you can do $data = htmlentities($data);

Save an image from canvas to WordPress media library (or server)

I am trying to implement functionality that allows users to save a png generated on a canvas element into a WordPress media library, or at least on the server (this is an intermediate step to sharing the image on facebook, which requires a valid image URL).
So far, I've just been doing everything with JavaScript, and am trying to save the image to the server with an AJAX call. So far, this is my AJAX:
$(document).on('click','.facebook',function(e){
var image = document.getElementById("canvas");
var imageURL = image.toDataURL();
$.ajax({
type: "POST",
url: "http://myexample.com",
data: {
imgBase64: imageURL
}
}).done(function(o) {
console.log('saved');
});
I guess I'm also a little unsure as to what is supposed to go in my url....I tried using the path for the images in my actual media library, but got a "permission denied" error when I tried to execute this.
Can anyone help?
There should be admin ajax URL. you can use the ajaxurl javascript variable to reference the admin-ajax.php file. However this variable is not declared on the frontend. It is simple to declare this on the front end, by putting the following in the header.php of your theme.
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
Then use it in your script like this:
$(document).on('click','.facebook',function(e){
var image = document.getElementById("canvas");
var imageURL = image.toDataURL();
$.ajax({
type: "POST",
url: ajaxurl,
data: {
imgBase64: imageURL
}
}).done(function(o) {
console.log('saved');
});
I'm not sure if WordPress has a REST API to upload images, so here is another approach: You can create your custom endpoint with the following action register_rest_route
Inside the function you can handle the image upload, heres an example of how to create a custom REST endpoint (http://example.com/imageHandler/v1/upload with type POST).
add_action( 'rest_api_init', function () {
register_rest_route( '/imageHandler/v1', '/upload', array(
'methods' => 'POST',
'callback' => 'uploadImage',
) );
} );
function uploadImage($request) {
$base64Image = $request['imgBase64'];
}
Inside the uploadImage function you might want to try this solution for uploading base64 images: https://gist.github.com/tjhole/3ddfc6cbf6da01c7ce0f since WordPress alone can't handle base64 uploads.
After uploading you can return the image url by calling: wp_get_attachment_url

How to upload a captured photo to REST interface using JSON - JQuery by PhoneGap (iPhone)?

My application asks from the user to capture an photo and then upload it to the server if the user is online. The code for the photo capture I took from PhoneGap API. How can I use the imgURL to upload it to the REST interface using Json and Jquery mobile?
The code I have up to now is:
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64 encoded image data
// console.log(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
Again, it is the same code taken from the PhoeGap API... I appreciate any help!...
Not sure if I understand your question correctly.
You should have your rest url and data structure (in JSON) the endpoint expects.
Once you have the base64 encoded string Use JSON library for packing JSON data and then send it to the service using
jquery.ajax().
Edited to include the post code
$.ajax({
type: 'POST',
url: yoururl,
data: jsondata,
success: success,
dataType: dataType
});
Content type will usually be
contentType: "application/json; charset=utf-8"
and datatype will be
dataType: 'json'

Categories

Resources