sending HTML5 canvas data via HTML post request - php

I want to send the canvas data to the server side as image. I have been making an HTTP post request, but i am not able to get the data at server side. $_POST is empty but when i console the same object at JS side i get the image data.
this is the JS side
var XHR = new XMLHttpRequest();
var vvFD="image=" + JSON.stringify(document.getElementById('canvas').toDataURL("image/png"));
console.log(vvFD);
XHR.upload.addEventListener('progress', uploadProgress, false);
XHR.addEventListener('load', uploadFinish, false);
XHR.addEventListener('error', uploadError, false);
XHR.addEventListener('abort', uploadAbort, false);
XHR.open('POST', 'example_upload/upload1.php');
XHR.send(vvFD);
and the PHP side is...
if(!empty($_POST))
{
//do stuff
}
else
{
echo "_POST is empty";
}
I am getting the message _POST is empty.
Any one can here help
Thanks in advance

I'm not entirely sure how your JS works, but I have a feeling it's sending the image in the body section of the HTTP request. $_POST won't pick that up on the server side.
Try:
$GLOBALS["HTTP_RAW_POST_DATA"];
There is an example in the manual which will output the headers from your HTTP request.
apache_request_headers()
Between these two, you should be able to capture everything coming into your php script.

Related

Save file from post response on button click in wordpress

A task:
The user, by clicking on the button, should be able to download and save the file.
The file is creating on another service. It can be obtained by post-request with body and headers.
I am using wordpress and my plugin. I can call a php function using form or jquery.
//Accept: application/pdf
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
$res = curl_exec($ch);
This returns the headers and response body as a string.
(My asp .Net 6 external service returns FileStreamResult from method)
I don't know how to implement saving a file on the user's PC.
As far as I understand, I have two ways:
Download the file using curl on the server side. Then somehow transfer the ready file to the user for saving.
But then there will be an extra load on the backend.
I can create request body and headers on backend. Then execute this post request on the client side.
I am weak in web development...
I think the right way is to make a function on the backend that will return a json with the request body and headers.
I can create a separate php page (I think it's redundant) that will call this function. Or I can call this function from javascript or jquery, but I don't know how to initialize post request to save the file.
Maybe someone has already implemented this behavior and can tell me?
Thanks.
upd. #1
I found this solution:
var request = new XMLHttpRequest();
request.responseType = "blob";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.onload = function() {
var url = window.URL.createObjectURL(this.response);
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = this.response.name || "filename"
a.click();
}
request.send(json);
But it looks like a dirty hack.
And it does not work as it should (the file is first downloaded before saving).
upd. #2
I'm willing to change the method from POST to GET, but I still need to pass the ApiKey in the header.
I think my issue is discussed here: https://github.com/whatwg/html/issues/7810
So far, I have not found a way that implements both points:
Adding custom headers to the request.
Showing the file save dialog before it is downloaded.

Outputting file contents as binary as AJAX response

OK the title doesn't give much a way so let me explain my very strange set-up.
Two servers are involved:
website: remote
localhost: local machine
The workflow is as follows:
The site calls localhost via cross-domain AJAX
In response localhost dynamically creates a ZIP file via PHP's ZipArchive lib
localhost conveys the raw data that comprises the archive as the AJAX response
The request is made and the archive is made - all good. The archive is openable, all good. What I'm stuck on now is how to convey that archive as the AJAX response, such that it can be "put together again" (à la Humpty Dumpty). When I do this currently (via file_put_contents()) it errors on opening, saying it's invalid. Currently I'm just outputting the archive's raw data:
echo file_get_contents('path/to/archive.zip');
This is fine, but sends garbled characters in the response. I don't know much about encoding and headers, so apologise if this seems obvious.
For the response, should I be looking to convert it to binary, or sending certain headers etc? I tried sending the multipart/form-data header, but no dice. Headers aren't my strong point.
Please note cURL is not an option in this scenario, else I'd be laughing.
You have to read the zip file as a binary data with Blob javascript class.
This is a code snippet from Mozilla documentation
var oReq = new XMLHttpRequest();
oReq.open("GET", "/myfile.png", true);
oReq.responseType = "arraybuffer";
oReq.onload = function(oEvent) {
var blob = new Blob([oReq.response], {type: "application/octet-stream"}); //
// you have nothing to do with the blob...
// ...
};
oReq.send();
Then send this file (blob) with POST method to your destination
var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.onload = function (oEvent) {
// Uploaded.
};
oReq.send(blob); //the blob that you loaded
you can read more in the documentation by Mozilla :https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

Server not seeing the JSON sent in javascript ajax request

I'm trying to make an ajax request in straight javascript (jQuery is not available to me) with some JSON parameters.
The javascript:
var params = {'ajax': true, 'albumid': albumid, 'sequencenum': sequencenum};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
console.log(xhr.responseText);
}
}
xhr.open("GET","viewpicture.php",true);
xhr.setRequestHeader("Content-Type", "application/json")
console.log("sending request");
xhr.send(JSON.stringify(params));
In viewpicture.php, a var_dump($_GET) yields an empty array. What am I doing wrong?
In short, when you make a GET request, .send is expected to have 0 params (or be null).
The only way to send the data through GET would be to append it to the URL itself.
To wit:
If you were sending in form-data, in a POST, the anticipation would be that send would contain the form-encoded data (json for json-data, etc), and the URL would just be the access point on the server.
A GET request is just fetching data from that access point (including query string).
See where I'm going with this?
So if you want this to work in a GET, you need to set your JSON as a property of a query parameter (or turn it into query params/values).
If you want to send in the request body you should use a POST request, however if you need to use a get request you should send the data as key value pairs in the url. e.g. xhr.open("GET","viewpicture.php?data=" + encodeURIComponent(JSON.stringify(params)),true); Then retrieve via $_GET['data'].

XMLHttpRequest sending XML to PHP server

I was wondering if I could send some data from my client-side (2d application using HTML5's canvas) to the server-side in the XML format?
I tried something like this:
function send_xml_data_to_server(xml, url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(xml);
xmlhttp.onreadystatechange = function() {
callback_response_from_server(xmlhttp);
}
}
Because in the informations that I must send to the server-side, it contains a few texts and it doesn't seem to work quite right with the the MIME:
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
But when I'm on the server-side I checked $_POST but there is nothing inside it, the same for $_REQUEST.
So, at the end, I was wondering if it is even possible to send XML data to the server-side PHP using XMLHttpRequest?
Thanks!
There's nothing wrong on the client side, but $_POST contains a parsed set of key/value pairs, but that's not what you're sending to the server. Use something like this:
file_get_contents('php://input');
Then you can parse the string using SimpleXML or whatever you like.
$_POST will be empty if you do not send data as application/x-www-form-urlencoded.
did you try this?
$xml = file_get_contents("php://input");
This way you will capture data in raw format and interpret it according to used mime type.

Asynchronous POST request from a Firefox's web worker

I am trying to make an asynchronous request with POST method from a web worker used in my extension. The thing is that it does not work for me.
On the server side I have PHP script listening for data in $_POST variable. Although I am able to establish connection to the server, and even pass some data in URL (GET), the $_POST is always empty.
Here is the latest code I'm using in the web worker:
var serviceUrl = "http://localhost/pfm/service/index.php";
var invocation = new XMLHttpRequest();
if(invocation){
invocation.open('POST', serviceUrl, true);
invocation.setRequestHeader('X-PINGOTHER', 'pingpong');
invocation.setRequestHeader('Content-Type', 'text/plain');
invocation.onreadystatechange = function(){processResponse(invocation);};
invocation.send("action=init");
}
(borrowed from MDN web site when I got an idea that the issue was the same origin policy)
Prior to this I was using a rather obvious and ridiculously simple:
var serviceUrl = "http://localhost/pfm/service/index.php";
var xhr = new XMLHttpRequest();
xhr.open("POST", serviceUrl, true);
xhr.onreadystatechange = function(){processResponse(receiptStoreRequest);};
xhr.send("action=init");
In this case the request also passed, but the $_POST was still empty.
Is it possible that POST-requests are not allowed on web workers?
Right now everything is being tested on localhost.
Don't set the content type text/plain but
invocation.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
In case you're developing for Firefox 4+ you might also be interested in FormData objects

Categories