weixin_33749242 2018-08-13 19:54 采纳率: 0%
浏览 62

使用AJAX的未定义索引[重复]

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined" dir="ltr">“Notice: Undefined variable”, “Notice: Undefined index”, and “Notice: Undefined offset” using PHP</a>
                            <span class="question-originals-answer-count">
                                (28 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2018-08-13 23:01:57Z" class="relativetime">2 years ago</span>.</div>
        </div>
    </aside>

I'm trying to send binary data using Ajax to upload in DB with PHP. I cannot acess the $_POST:

responseText:

Notice: Undefined index: obBlob in C:\xampp\htdocs\WEBCAM\upload.php on line 4

AJAX 'error':

{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …} abort : ƒ (e) always : ƒ () catch : ƒ (e) done : ƒ () fail : ƒ () getAllResponseHeaders : ƒ () arguments : (...) caller : (...) length : 0 name : "getAllResponseHeaders" prototype : {constructor: ƒ} proto : ƒ () [[FunctionLocation]] : jquery-3.3.1.min.js:2 [[Scopes]] : Scopes[3] getResponseHeader : ƒ (e) overrideMimeType : ƒ (e) pipe : ƒ () progress : ƒ () promise : ƒ (e) readyState : 4 responseText : "Nenhuma imgagem encontrada" setRequestHeader : ƒ (e,t) state : ƒ () status : 200 statusCode : ƒ (e) statusText : "OK" then : ƒ (t,r,i) proto : Object

Code:

index.html (full):

<!doctype html>
<html lang="pt">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
        <title>Webcam TRIX</title>      
    </head>
    <body>
        <video src="" id="video" muted autoplay></video>
        <canvas id="pic"></canvas>
        <!--  colocar um form com um action para salvar a foto -->
        <input type="text" id="blobOut" value="">
        <img alt="" src="" id="picOut"/>Foto
        <input type="button" id="btnStart" value="Tirar Foto">
        <input type="button" id="btnSave" value="Salvar Foto">
        <script type="text/javascript">
            //inicializa um objeto stream
            var tmpStream;
            function setMedia(video, s){
                tmpStream=s;
                try{
                    video.srcObject = s;
                }catch(error){
                    video.src = URL.createObjectURL(s);
                }
            }
            //função para iniciar a camera
            function startCamera(){
                navigator.mediaDevices.getUserMedia({
                    video:{facingMode:"environment"},
                    audio: true
                })
                .then((stream) => {
                    setMedia(document.getElementById("video"),stream);
                });
            }
            //função para parar a camera
            function stopCamera(){
                if(!tmpStream) return;
                tmpStream.getVideoTracks().forEach(track => track.stop());
            }
            //ligar a camer automaticamente
            window.addEventListener("DOMContentLoaded", startAll);
            //incicializa tudo
            function startAll()
            {
                startCamera();
                //função para tirar foto
                document.querySelector("#btnStart").addEventListener("click", event => {
                    canvas = document.getElementById("pic");
                    const context = canvas.getContext("2d");
                    const video = document.getElementById("video");
                    //tamanho da foto mesmo tamanho do video
                    canvas.width = video.offsetWidth;
                    canvas.height = video.offsetHeight;
                    //desenha o video no canvas
                    context.drawImage(video, 0, 0, canvas.width, canvas.height);
                });
            }
            document.getElementById("btnSave").addEventListener("click", event => {
                            canvas.toBlob(function(blob){
                                $.ajax({
                                    url : "upload.php",
                                    type: "POST",
                                    data: {obBlob: blob},
                                    contentType: false,
                                    processData: false,
                                    dataType:"json",
                                    success: function(resultado) {
                                      console.log(resultado);
                                    },
                                    error: function(resultado) {
                                        console.log(resultado);
                                    }
                                });
                            });
                        });
        </script> 
    </body>
</html>

upload.php (full):

<?php
header("Content-Type: application/json", true);
if(empty($_POST["obBlob"])) die("Nenhuma imgagem encontrada");
$obBlob = $_POST["obBlob"]; 
$servername = "localhost";
$username = "root";
$password = "";
$database = "fotos";
$conn = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO fotos (foto) VALUES ($obBlob)";
if(mysqli_query($conn, $sql)){
    mysqli_close($conn);
}else{
    $error = $conn->error;
    mysqli_close($conn);
    die($error);
}
?>

EDIT:

I have tried using the API FormData with AJAX, but no success:

document.getElementById("btnSave").addEventListener("click", event => {
                            canvas.toBlob(function(blob){
                                var formData = new FormData();
                                formData.append("obBlob", blob);
                                $.ajax({
                                    url : "//localhost/webcam/upload.php",
                                    type: "POST",
                                    data: {obBlob: formData},
                                    contentType: false,
                                    processData: false,
                                    success: function(resultado) {
                                      console.log(resultado);
                                    },
                                    error: function(resultado) {
                                        console.log(resultado);
                                    }
                                });
                            });
                        });

i have tried using XMLHttpRequest without AJAX... converting to JSON or not:

document.getElementById("btnSave").addEventListener("click", event => {
                    canvas.toBlob(function(blob){
                        json = JSON.parse(JSON.stringify(blob));
                        console.log(json);
                        var xhr = new XMLHttpRequest();
                        xhr.open("POST", 'upload.php', true);
                        xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
                        xhr.send(json);
                    });
                });

EDIT 2:

I gave up using blob type and tried with canvas.toDataURL, but the array arrives empty:

document.getElementById("btnSave").addEventListener("click", event => {
                var dataURL = canvas.toDataURL();
                $.ajax({
                    url : "//localhost/webcam/upload.php",
                    type: "POST",
                    data: {"imgBase64":dataURL},
                    contentType: false,
                    processData: false,
                    dataType:"json",
                    success: function(resultado) {
                      console.log(resultado);
                    },
                    error: function(resultado) {
                        console.log(resultado);
                    }
                });
            });

When I verify the payload in network tab of the dev tools of Chrome, the object is there!

I have tried a lot of things but still not working... I have verified the $_SERVER['REQUEST_METHOD'] and it returns POST, I have no idea of what is going on... I'm at the root of trial and error!

</div>
  • 写回答

1条回答 默认 最新

  • weixin_33682719 2018-08-13 20:19
    关注

    try this

    var formData = new FormData()
    
    formData.append("obBlob", blob);
    
    var request = new XMLHttpRequest();
    request.open("POST", "//localhost/webcam/upload.php");
    request.send(formData);
    
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大