Undefined index in value pass with AJAX

Asked

Viewed 271 times

1

I am trying to send binary Blob data by Ajax to upload via PHP. However, I am unable to access $_GET. Returns an error saying undefined index:

responseText : "No imgagem found"

when I comment the upload.php die() line:

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

Return of 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 : voltar () [[Functionlocation]] : jquery-3.3.1.min. js:2 [[Scopes]] : Scopes[3] getResponseHeader : voltar (e) overrideMimeType : voltar (e) pipe ě () Progress : ě () Promise : ě (e) readyState : 4 responseText : "No imgagem found" setRequestHeader : ?(e,t) state : ŋ () status : 200 statusCode : ː(e) statusText : "OK" then : made up (t,r,i) proto : Object

follows the code:

index.html (complete):

<!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($_GET["obBlob"])) die("Nenhuma imgagem encontrada");
$obBlob = $_GET["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);
    echo $conn->error;
}else{
    mysqli_close($conn);
    die("Error:".$conn->error);
}
?>

EDIT:

tried as follows, using the Formdata API with AJAX, unsuccessfully:

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);
                                    }
                                });
                            });
                        });

and tried so too, by sending the manual... I tried sending the blob directly, or converting to JSON (which in case is empty when I play on the console!):

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);
                    });
                });

How do I catch the error in this last case? some idea of what might be?

EDIT 2:

I gave up using blob 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 check the payload in the network tab of the Chrome developer tools the object is la!

I tried everything and did not leave said... I checked the $_SERVER['REQUEST_METHOD'] and is returning POST, I tried to pass using Xmlhttprequest... I have no idea what it might be... I’m at the base of trial and error!

  • You are performing POST but is recovering the variable via $_GET

  • jQuery AJAX does not allow type blob, have to make a request in hand or use some other library

1 answer

0


I was able to solve the problem using a Formdata object by adding an index to the object that I would like to move from JS to PHP with the "append()" method. and then passing the Formdata object using the Xmlhttprequest send method...

document.getElementById("btnSave").addEventListener("click", event => {
   var fd = new FormData();
   var dataURL = canvas.toDataURL('image/jpeg', 1.0);
   fd.append("data", dataURL);
   var oReq = new XMLHttpRequest();
   oReq.open("POST","upload.php");
   oReq.send(fd);
});

To access is used the $_POST normally, accessing the index created in the Formdata object. ex of the above code:

$_POST['date']

Thank you all for your help!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.