I have a script that opens a camera and takes a snap. I want it to be able to create an id of the photo and then store it.

HTML

  <a href="javascript:void(0);" class="updateControl2" id="webcamButton" title="Open Camera"><span class="boxWebcam wallbutton">Open Camera</span></a><br /><br /><br />
                <video id="player" controls autoplay></video>
                <div id="webcam">
                <button  id="takeSnap" class="camclick  wallbutton">Capture</button>
                <canvas id="snapshot" width=320 height=240></canvas>
                 <input type="hidden" id="uploadvalues">
            <input type="hidden" id="upload_uid" value="<?php echo $sessionUid;?>" name="update_uid">
            <input type="hidden" id="upload_token" value="<?php echo $sessionToken;?>" name="update_token">
            <input type="hidden" id="group_id" value="<?php echo $groupID; ?>" name="group_id">

JAVASCRIPT

$("body").on("click",'.updateControl2',function()
    {
        var ID=$(this).attr("id");
        if(ID=='webcamButton')
        {   

            var player = document.getElementById('player'); 
            var snapshotCanvas = document.getElementById('snapshot');
            var captureButton = document.getElementById('takeSnap');

            var handleSuccess = function(stream) {
            // Attach the video stream to the video element and autoplay.
            player.srcObject = stream;

        };

        captureButton.addEventListener('click', function() {
            var context = snapshot.getContext('2d');
            // Draw the video frame to the canvas.
            context.drawImage(player, 0, 0, snapshotCanvas.width, 
            snapshotCanvas.height);

        });
        navigator.mediaDevices.getUserMedia({video: true})
      .then(handleSuccess);
        }
 return false;
    });

PHP works fine

function webcamImageCreate()
{
    $request = \Slim\Slim::getInstance()->request();
    $x = $request->post();
    $uid=$_POST['uid'];
    $token=$_POST['token'];
    $group_id=$_POST['group_id'];
    try
    {
        $key=md5(SITE_KEY.$uid);
        if($key==$token)
        {
            $invalid = "iVBORw0KGgoAAAANSUhEUgAAAUAAAADwCAYAAABxLb1rAAAG+UlEQVR4Xu3UgREAIAgDMdl/aPFc48MGTbnOfXccAQIEggJjAIOti0yAwBcwgB6BAIGsgAHMVi84AQIG0A8QIJAVMIDZ6gUnQMAA+gECBLICBjBbveAECBhAP0CAQFbAAGarF5wAAQPoBwgQyAoYwGz1ghMgYAD9AAECWQEDmK1ecAIEDKAfIEAgK2AAs9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ghMgYAD9AAECWQEDmK1ecAIEDKAfIEAgK2AAs9ULToDAAoCVvV4Lh4uLAAAAAElFTkSuQmCC";

            if ($_POST['type'] == "pixel")
            {
                $image = $_POST['image'];
                $filter_image = str_replace("data:image/png;base64,", "", $image);
                // input is in format 1,2,3...|1,2,3...|...
                if($filter_image == $invalid)
                {
                    $im = "";
                    echo "false";
                }
                else
                {
                    $im = imagecreatetruecolor(320, 240);
                    foreach (explode("|", $_POST['image']) as $y => $csv) {
                        foreach (explode(";", $csv) as $x => $color) {
                            imagesetpixel($im, $x, $y, $color);
                        }
                    }
                }
            } else {
                // input is in format: data:image/png;base64,...
                $image = $_POST['image'];
                $filter_image = str_replace("data:image/png;base64,", "", $image);
                if($filter_image == $invalid)
                {
                    $im = "";
                    echo "false";
                }
                else
                    $im = imagecreatefrompng($_POST['image']);
            }

            if($im)
            {

                $filename=time().$uid.".jpg";
                if(empty($conversationImage))
                {
                    $conversationImage='';
                }
                internalImageUpload($uid,$filename,$group_id,$conversationImage);
                //imagejpeg($im);

                $upload_path='../'.UPLOAD_PATH;
                imagejpeg($im, $upload_path.$filename);
                $imageID=internalGetUploadImage($uid,$filename);
                $fullImagePath=BASE_URL.UPLOAD_PATH.$filename;
                //echo '{"webcam": [{"imageName":"'.$fullImagePath.'", "imageID":"'.$imageID[0]->id.'" }]}';
                imagedestroy($im);
                echo "<img src='".$fullImagePath."'  class='webcam_preview' id='".$imageID[0]->id."'/>";
            }

        }

    }
    catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
}

And now i want to implement a javascript code that will call the var webcamURL=apiBaseUrl+'api/webcamImageCreate'; function

This is what i got but it doesn't work it doesn't to call the function
I opens the camera as wanted takes a snap but doesn;t call the php function or shows any errors on console

var xtype="data";
    var ximage=canvas.toDataURL("image/png");
    var webcamURL=apiBaseUrl+'api/webcamImageCreate';
    $.post(webcamURL, {uid:uid, token:token,group_id:groupID, type: "data", image: canvas.toDataURL("image/png")},
    function(data)
    {
    if(data)
    {
                var values=$("#uploadvalues").val();
                $("#snapshot").prepend(data);
                var X=$('.webcam_preview').attr('id');
                if($.trim(values).length>0)
                {
                var Z= X+','+values;   
                }
                else
                {
                var Z= X;  
                }

                if(Z!='undefined,')
                {
                $("#uploadvalues").val(Z);
                }
    }
Member Avatar for diafol

So are you populating the form OK with the snap? Do you just need an Ajax submit to the php script? Do you need to return the db ID in the response?

Yes i need to retunr the ID and call the php function

Member Avatar for diafol

You can do this:

$.post(webcamURL, {uid:uid, token:token,group_id:groupID, type: "data", image: canvas.toDataURL("image/png")},
    function(data)
    {
        if(data)
        {
                    console.log(data);
        }
    });

But the main thing is to store the image (or its location/filename) in a db, retrieve its ID and send back (by echoing):

<?php
    if($_POST) 
    {
        //use pdo or mysqli
        //store either the image itself (BLOB) or the filename via INSERT query
        //retrieve the ID using lastInsertId (PDO) or insert_id (msqyli), then:
        echo $id;
    }

That should pass the ID to the data parameter in the ajax code. You may want to get a little more technical with error handling though.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.