I'm aware that this question was answered in this forum (Unable to get values in POST php web serivce), but both the question and the answer used jQuery and, in my case, I can't use it (no matter why)...
So, I have a Javascript file that is intended to make a canvas' "screen capture" (using the "toDataURL()" function) and send it to a PHP file using AJAX. As the data to be sent is really long, I can't use the "GET" method (AJAX returns a 414 error: "URL TOO LONG"), so I need to use "POST".
I've followed some examples on plain Javascript (which are by no means easy to find, because everyone uses jQuery! :P) and my code looks like this:
var dataURL = me.video.getScreenCanvas().toDataURL();
var req = false;
try{
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
req.onreadystatechange = function(){
if(req .readyState == 4){
if(req.status == 200)
{
console.log("RESULT AJAX: "+req.responseText);
}else{
console.log("ERROR AJAX: returned status code "+req.status+" "+req.statusText);
}
}
}
req.open("POST", "http://www.mywebpage.com/image_upload.php", true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send("imgdata="+dataURL);
When trying to log the content of the "dataURL" variable, it logs a large string like "image/png...blablabla", so I presume the data is generated as expected.
At this moment, the PHP file just tries to retrieve the result:
<?php
$imageData = '';
if(isset($_POST['imgdata']))
{
echo "correct POST!";
$imageData = $_POST['imgdata'];
}else if(isset($_GET['imgdata'])){
echo "correct GET!";
$imageData = $_GET['imgdata'];
}
echo "ImgData: ".$imageData;
if($imageData != '')
{
$imageData = str_replace(' ','+',$imageData);
$decodedData = base64_decode($imageData);
if(file_put_contents('imatge1.jpeg', $decodedData) !== FALSE)
{
echo "Image has been successfully processed...?";
}else{
echo "Error trying to process the image...";
}
}
?>
However, the PHP file doesn't echo the "POST" nor the "GET" messages, the "ImgData" echo returns empty and no "success" nor "error while processing image" message is echoed... So it seems that the PHP file is not able to retrieve the data passed by AJAX's "POST" method.
What am I doing wrong? How could I solve this problem using just plain Javascript (it's important not to use jQuery)?
Thanks in advance for your time and effort! :)