AJAX sending a base64 image to an external server - php

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.

Related

Saving a file locally instead of on the server

I have a php script which opens a csv file, edits it, then saves it using 'file_put_contents'. The saved location is the same server directory which contains the script.
file_put_contents($destination,$string);
However, I want the user to have control over where the file is saved on their computer (ie. locally.) Preferably, using a dialogue pop-up on their browser.
How would this be achieved? Do I need to add header information to the php script? Thanks in advance.
To save file in local with popup of window you can use JS (Blob Object) for it :
// ajax get data from server ( you can push file to server for editting it and return)
// data return of php : return stream_get_contents($file);
$.ajax({
type: "post",
url: url,
data: {...},
success: function (data) {
let blob = new Blob([data], { type: 'application/csv;charset=utf-8;' });
handleSaveCsv(blob);
}
});
async function handleSaveCsv(blob){
if( window.showSaveFilePicker ) {
const handle = await showSaveFilePicker({
suggestedName: 'csvExportName.csv',
types: [{
description: 'csv file',
accept: {'application/csv': ['.csv']},
}],
});
const writable = await handle.createWritable();
await writable.write( blob );
writable.close();
}
else {
const saveCsv = document.createElement( "a" );
saveCsv.href = URL.createObjectURL( blob );
saveCsv.download= 'csvExportName.csv';
saveCsv.click();
setTimeout(() => URL.revokeObjectURL( saveCsv.href ), 6000 );
}
}
window.showSaveFilePicker for opening popup window

ajax post then get file to use

I am new on php, and I am writing a code which allows me to send some data to php then doing some exec(), and then get the process output back to use(e.g. post one web page).
$.ajax({
url: 'some.php',
type: 'POST',
data: someData,
async: false,
success: function (html) {
$('#showonscreen').html(html);
},
cache: false,
contentType: false,
processData: false
});
and on php part is like
<?php
/*something like $cmd here*/
exec("$cmd $target_file $Output_fileName $upper $lower");
echo "<br/>done";
?>
after that exec() generates a output file (e.g image)with that Output_fileName under the root folder.
My question is can I get(or load?) this file directly back client side to use?(in success part?) Or I need a $.get to request from server again to get that file?
So, on client side, it works like, they upload a image, then click button to process it, then the result image is store under server root, then grab from it to show on the web page.
any help
On Server Side
First its good if you capture o/p like below
exec('your_command 2>&1', $outputAndErrors, $return_value);
Then
if (!$return_value) {
// Ok lets decide what next
} else {
// Ooops some problem error handling
}
As you mentioned if you are dealing with image then
echo base64_encode(file_get_contents($your_file_generated));
for plain text you can just
header('Content-type: text/plain; charset=utf-8');
echo file_get_contents($your_file_generated);
// OR
echo readfile($your_file_generated);
On Client Side
$.ajax({
..
..
success: function (server_response) {
$('#showonscreen').html('<img src="data:image/png;base64,'+ server_response +'"/>');
},
..
..
});

Codeigniter : Multiple File Uploading

I tried many multiple file uploaders which can be integrated with codeigniter like
pulpload
jquery file upload
Even though they work perfectly in the pure php environment, i could not make them work in codeigniter framework. I tried this for two days.. tried many articles which was in the github and blogs..
But i could not made it in codeigniter framework..
If anyone can tell me it by step by step or if there is a tutorial for that, please help me.
I am a newbi to codeigniter..
New:
I downloaded the blueimp Jquery-File-Upload plugin, and followed this link as it is..
https://github.com/blueimp/jQuery-File-Upload/wiki/Latest-jQuery-File-Upload-easy-integration-with-codeigniter
When I select a file and click upload in chrome it says:
Error SyntaxError: Unexpected token <
In firefox it says:
Error SyntaxError: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I examined the difference between using it on my server and on the demo server, on my server in firebug the POST return is the entire index.html...
but on the demo server it returns JSON data..
Here is the modified section of js/main.js that I changed:
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: 'upload/do_upload'
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'blueimp.github.io') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
}
});
The only thing I changed was making index.html to have the form action point to my script (upload/do_upload)
controller
function add()
{
if(isset($_POST['submit']))
{
$length = count($_FILES['image']['name']);
$filename = $_FILES['image']['name'];
$tempname = $_FILES['image']['tmp_name'];
$allimage = array();
foreach($filename as $key =>$value)
{
move_uploaded_file($tempname[$key],'media/uploads/mobile_product/'
.$filename[$key]);
$allimage[] = $filename[$key];
}
if(!empty($allimage))
{
$allimage = json_encode($allimage);
}
else
{
$allimage = '';
}
$data['image'] = $allimage;
$this->db->insert('table_name',$data);
$this->session->set_flashdata('message','<div class="alert alert-success">Record has been successfully saved.</div>');
}
}

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