Unable to get AJAX's post values (plain Javascript)

佐手、 提交于 2019-12-25 01:46:35

问题


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! :)


回答1:


I changed your javascript, and tested this, please try if it work with you :

function create_XHR(){
    var XHR = null;
    if (window.XMLHttpRequest){
        XHR = new XMLHttpRequest();
    }
    else if(window.ActiveXObject){
        try {
            XHR = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            XHR = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    else {
        alert("Your navigator is old to run objets XMLHTTPRequest...");
        XHR = false;
    }
    return XHR;
}


function ajax_post(page, data) {

    var XHR = create_XHR();
    XHR.open("POST", page, true);
    XHR.onreadystatechange = function() {
        if (XHR.readyState === 4 && (XHR.status === 200 || XHR.status === 0)) {
            console.log("Success Transaction");
        }
    };
    XHR.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    XHR.send(data);
}


//Running the code :
//==================
var dataURL = me.video.getScreenCanvas().toDataURL();
ajax_post("http://www.mywebpage.com/image_upload.php", {"imgdata":dataURL});

Modify the cors http : in the server PHP add this in first of your page "image_upload.php":

//Part added by ilyas :
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }
//End of part.



回答2:


I think that you need to configure you server apache in file httpd.conf

Under Apache, the limit is a configurable value, LimitRequestLine. Change this value to something larger than its default of 8190 if you want to support a longer request URI.

change :

LimitRequestLine 4094

to a value < 8190



来源:https://stackoverflow.com/questions/23673796/unable-to-get-ajaxs-post-values-plain-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!