I am using Fabric.js canvas library, and I want to save the canvas on the server.
Converted it into data URL:
var canvasData = canvas.toDataURL();
and sent it to the server using Ajax:
let xhr = new XMLHttpRequest();
xhr.open("POST", "php/saveImg.php", true);
xhr.onload = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
let data = xhr.response;
window.open(data);
}}};
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("canvasData=" + canvasData);
decoded the data and saved it in saveImg.php:
if(isset($_POST['canvasData'])){
$imageData = $_POST['canvasData'];
echo $imageData;
$filteredData = substr($imageData, strpos($imageData, ",") + 1);
$a = file_put_contents( "images/image1.png", base64_decode($filteredData));
}
When I look into image1.png, it is transparent with nothing in it (yet it has the right dimensions and a size of 40 KB).
When I check the value that is received in $_POST, I can see that the value of the data is deformed: some + characters have been removed and some other chars have been added.
Your POST data is not encoded properly, you can use encodeURIComponent to do this
xhr.send("canvasData=" + encodeURIComponent(canvasData));
Related
I want to send numerical data through a GET retrieved via Javascript GPS position.coords.latitude here is the code.
function post() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
var v2 = -20.9008623; //position.coords.latitude;
var v3 = 55.4958068; //position.coords.longitude;
var v4 = v2.toString();
var v5 = v3.toString();
xmlhttp.open("POST", "ajax.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("LAT=" + v4 + "&LON=" + v5);
}
As you can see, var2 and var3 are numeric data and are indeed sent in this case since they are converted into a character string before being sent by the GET.
On the other hand as soon as I do the recovery by position.coords.latitude nothing is sent or rather nothing is recovered by the AJAX file.
Did I forget something? Thank you for your answers.
You cant send anything else then strings with urlencoded content. Use another format.
Try with a FormData for instance.
const data = new FormData()
data.append('lat', 37)
data.append('long', 32)
xmlhttp.setRequestHeader('content-type: multipart/form-data;')
xmlhttp.send(data)
How can I best format my POST request for the Cisco API CompressedClientLog?
https://developer.cisco.com/docs/finesse/#!compressedclientlog%e2%80%94post-compressed-log-to-finesse/compressedclientlogpost-compressed-log-to-finesse
CompressedClientLog—Post Compressed Log to Finesse
var data = new FormData();
var logObj = '<ClientLog><logData>This is some logged data for the log file</logData></ClientLog>';
data.append("logData", logObj);
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log("Gadget is now engaged" + this.responseText);
}
});
xhr.open("POST", "https://finesse1.xyz.com/finesse/api/User/finadmin/CompressedClientLog");
xhr.send(data);
Response is:
<ApiErrors>
<ApiError>
<ErrorType>Parameter Missing</ErrorType>
<ErrorData>logData</ErrorData>
<ErrorMessage>Missing logData in the ClientLog object</ErrorMessage>
</ApiError>
</ApiErrors>
Where am I going wrong?
I am trying to send the data in XMLHttpRequest through json, in the log I receive succesful and the data info correctly but in the php I cannot collect the data,this works with an exit() and the $data on the php file, if you take out $data it the responseText is empty, if you take out exit(), it transforms into some weird characters with ? and more nonsense, and if you use $_POST it shows array() and some weird characters again after the empty array. The js part is sent when you click on the chart.js and then it is accessed from report.php when clicking on an icon, I don't know if when accessing like this the info from the js is not arriving, as I just get a blank page. This is the js and the php:
onComplete: function() {
console.log(myChart.toBase64Image());
var imgData = myChart.toBase64Image();
var imgRes = imgData.replace('data:image/png;base64,', '');
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == XMLHttpRequest.DONE) {
console.log(xhttp.responseText);
if (xhttp.status === 200) {
console.log('successful');
} else {
console.log('failed');
}
}
}
xhttp.open("POST", base_url_admin+"record/reporte", true);
xhttp.setRequestHeader("Content-type", "application/json");
let data = JSON.stringify({"resultChartImg": imgRes});
xhttp.send(data);
}
php:
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);exit();
Error Image of the weird characters
I have trouble in accessing the JSON string being sent from my client side Javascript code to my PHP code. This is what I have done until now.
var formatted;
fr.onload = function(e) {
var result = JSON.parse(e.target.result);
formatted = JSON.stringify(result, null, 2);
console.log(formatted);
//send formatted as post to write2share.php and write that in a file in share folder
xhr = new XMLHttpRequest();
var url = "write2share.php";
var nametime = gettime();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", 'application/json; charset=UTF-8');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.content);
}
}
var data = JSON.stringify({"content":formatted, "name": nametime});
xhr.send(data);
//GenerateShare(nametime);
}
Here formatted is a JSON string and nametime is an integer
The below is my php script
$decoded = json_decode(file_get_contents("php://input"),true);
$error = json_last_error();
var_dump($decoded);
echo $error;
The output of my $error is 0 and var_dump of $decoded is Null. Why?
Help is appreciated! Thanks
I am trying to upload a image to server,In that i have converted image to base64encode string and i need to pass that base64encode string to webservice,that webservice convert the base64 string to file and saving in database.but base64encode string has huge length approximately(85,000) when i pass this string to webservice i am getting the following error.
Failed to load resource: the server responded with a status of 400 (Bad Request)
i need to pass this by using only XMLHttpRequest() with out using the ajax,jquery please help me.
below is my code.
var filesToBeUploaded = document.getElementById("afile");
var file = filesToBeUploaded.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var binaryStringResult = reader.result;
var binaryString =binaryStringResult.split(',')[1];
var xhr = new XMLHttpRequest();
xhr.open("POST","http://url/api/jsonws/Global-portlet.org_roles/add-file-entry?repositoryId=11304&folderId=0&sourceFileName=test108.jpeg&mimeType=image%2Fjpeg&title=test108.jpeg&description=test108.jpeg&changeLog=test108.jpeg&basecode64="+ binaryString);
xhr.setRequestHeader("Authorization","BasicbmFyYXlhbmFAdmlkeWF5dWcuY29tOnRlc3Q=");
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send();
xhr.onload = function() {
alert('in sucess');
};
xhr.onerror = function(e) {
alert('in error');
};
}
reader.readAsDataURL(file);
For POST, don't include it in the URL, you need to put it in the body, i.e.
xhr.send(binaryString);
I doubt your Content-Type of application/x-www-form-urlencoded is correct in this case.
I think the issue that you encountering here is that you are exceeding the maximum length of a query string.
What you need to do is something like the following:
var xhr = new XMLHttpRequest();
var url = "http://url/api/jsonws/Global-portlet.org_roles/add-file-entry";
var params = "repositoryId=11304&folderId=0&sourceFileName=test108.jpeg&mimeType=image%2Fjpeg&title=test108.jpeg&description=test108.jpeg&changeLog=test108.jpeg&basecode64="+ binaryString;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(params);
Hope that helps