In the software I am building, I am using the webcam to take a picture and from there upload it to the PHP server for later usage. I have successfully uploaded images from my computer to the server using a form, but since the image I want to upload is already pre-decided, I've been looking into using AJAX. My code for taking the snapshot from the webcam is as follows:
var video = document.getElementById('video');
// Get access to the camera!
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// Not adding `{ audio: true }` since we only want video now
navigator.mediaDevices.getUserMedia({video: true}).then(function (stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
});
}
// Elements for taking the snapshot
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('video');
// Trigger photo take
document.getElementById("snap").addEventListener("click", function () {
var img = context.drawImage(video, 0, 0, 640, 480);
});
document.getElementById("capture").addEventListener("click", function () {
context.drawImage(video, 0, 0, 640, 480);
//var capture = canvas.toDataURL();
});
This is my php code which saves this image:
<?php
if (isset($_POST['upload'])) {
$image_name = $_FILES['image']['name'];
$image_name = $_FILES['image']['type'];
$image_name = $_FILES['image']['size'];
$image_tmp_name = $_FILES['image']['tmp_name'];
if ($image_name == '') {
echo "<script>alert('Please select an image.')</script>";
exit();
} else {
move_uploaded_file($image_tmp_name, "pictures/$image_name");
echo "Image uploaded succesfully.";
echo "<img src= 'pictures/$image_name'>";
}
}
?>
I am sure that both of these bits of code work since I have tested them separately. As stated before, I am trying to tie them together using AJAX. The sample code I found for this is:
function saveImage() {
var capture = canvas.toDataURL("image/png");
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.open('POST', 'picture.php', false);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.onreadystatechange = function () {
console.log(ajax.responseText);
}
ajax.send("imgData=" + capture);
}
I used onClick = "saveImage()" within a button to try a call the function an upload the image to the server. When I hit the button, the file doesn't seem to access the server at all. Is there something I am missing here to make it all work?