I have a file that's called camera.php, here is the source bellow :
camera.php
<div id="video" style="margin: auto;text-align:center;">
<video autoplay id="vid"></video>
</div>
<button id="start" class="btn" onclick="Start()">Start</button>
<button id="stop" class="btn" onclick="Stop()">Stop</button>
<button id="takeshot" class="btn" onclick="TakeShot()">TakeShot</button>
<canvas id="canvas" width="640" height="480"></canvas>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
video = document.getElementById('vid');
function Start() {
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({video : true}).then((stream) => {
video.srcObject = stream;
});
}
else
console.log('ur navigator does not support getUserMedia !!');
}
function Stop() {
if (video.srcObject)
video.srcObject = undefined;
}
function TakeShot() {
if (video.srcObject) {
canvas = document.getElementById('canvas');
gtc = canvas.getContext('2d');
gtc.drawImage(video, 0, 0);
imgData = canvas.toDataURL('image/png');
//gtc.clearRect(0, 0, canvas.width, canvas.height);
pb = document.getElementById('pb').value;
pub(imgData, pb);
}
else
console.log('you need to use Webcam to take a shot');
}
function pub(img, pb) {
// using jquery.post() to send request
$.post('https://xxxxxx.com/camera/save', {'img' : img, 'pub' : pb, 'stick' : stickSelectd}, (result) => {
obj = JSON.parse(result);
if (obj.error == true) {
document.getElementById('msg').innerHTML = obj.msg;
}
else
document.getElementById('msg').innerHTML = 'Publication has been added';
}).done(() => {
alert('request is done');
}).fail(() => {
alert('request is fail');
});
// using jquery.ajax() to send post request
$.ajax({
url : 'https://xxxxxx.com/camera/save',
method : 'POST',
data : {
'img' : img, 'pub' : pb, 'stick' : stickSelectd
},
headers : "Content-type : image/png",
Success : (result) => {
alert(result);
},
err : () => {
alert('error');
}
});
}
</script>
.htaccess I know too many risks for allow-origin "*" but i use it just for testing.
Header Set Access-Control-Allow-Origin "*"
always request sending by $.post() alert 'request is fail' and sometimes the request is received from the server and save the image but the meme respond is getting ('request is fail').
there is all fine in my code or i miss something like headers, .. ?? and thanks for helping
it works now with ajax(), i change the function pub to :
i don't know why the old syntax doesn't work, I think it fine ?!