title: I want to send webcam video data in database on button click through AJAX
body: <p><strong>index.php</strong></p>
  
  <p>In this file I create webcam and create buttons record, save, stop.</p>
  
  <pre><code>    &lt;html&gt;
          &lt;head&gt;
  
          &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
          &lt;meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes"&gt;
          &lt;meta name="mobile-web-app-capable" content="yes"&gt;
          &lt;meta id="theme-color" name="theme-color" content="#fff"&gt;
          &lt;!--&lt;base target="_blank"&gt;--&gt;
          &lt;title&gt;Access Webcam Device&lt;/title&gt;
          &lt;link rel="stylesheet" href="today/main.css" /&gt;
          &lt;link rel="stylesheet" type="text/css" href="style.css"&gt;
          &lt;/head&gt;
          &lt;body&gt;
      &lt;?php
      session_start();
      $sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
      if(!empty($sessData['status']['msg'])){
          $statusMsg = $sessData['status']['msg'];
          $statusMsgType = $sessData['status']['type'];
          unset($_SESSION['sessData']['status']);
      }
      ?&gt;
  
          &lt;?php
              if(!empty($sessData['userLoggedIn']) &amp;&amp; !empty($sessData['userID'])){
                  include 'user.php';
                  $user = new User();
                  $conditions['where'] = array(
                      'id' =&gt; $sessData['userID'],
                  );
                  $conditions['return_type'] = 'single';
                  $userData = $user-&gt;getRows($conditions);
          ?&gt;
          &lt;div class="tech"&gt;
          &lt;header&gt;
             &lt;h1&gt;Header&lt;/h1&gt;
             &lt;div class="log"&gt;&lt;span&gt;Welcome &lt;?php echo $userData['first_name']; ?&gt;!&lt;/span&gt;&amp;nbsp;&amp;nbsp;&lt;a href="userAccount.php?logoutSubmit=1" class="logout"&gt;Logout&lt;/a&gt;&lt;/div&gt;
          &lt;/header&gt;
          &lt;!--&lt;div class="main"&gt;--&gt;
          &lt;div class="regisFrm"&gt;
              &lt;!--&lt;p&gt;&lt;b&gt;Name: &lt;/b&gt;&lt;?php //echo $userData['first_name'].' '.$userData['last_name']; ?&gt;&lt;/p&gt;
              &lt;p&gt;&lt;b&gt;Email: &lt;/b&gt;&lt;?php //echo $userData['email']; ?&gt;&lt;/p&gt;
              &lt;p&gt;&lt;b&gt;Phone: &lt;/b&gt;&lt;?php //echo $userData['phone']; ?&gt;&lt;/p&gt;--&gt;
              &lt;div id="container"&gt;
                  &lt;div style = "text-align:center;"&gt;
                      &lt;h1&gt;Webcam Recorder &lt;/h1&gt;
  
                      &lt;video controls autoplay&gt;&lt;/video&gt;&lt;br&gt;
                      &lt;button id="rec" onclick="onBtnRecordClicked()"&gt;Record&lt;/button&gt;
                      &lt;button id="pauseRes"   onclick="onPauseResumeClicked()" disabled&gt;Pause&lt;/button&gt;
                      &lt;button id="stop"  onclick="onBtnStopClicked()" disabled&gt;Stop&lt;/button&gt;
                      &lt;button id="saveBtn" &gt;Save&lt;/button&gt;
                   &lt;/div&gt;
                  &lt;a id="downloadLink" download="mediarecorder.webm" name="mediarecorder.webm" href&gt;&lt;/a&gt;
                  &lt;p id="data"&gt;&lt;/p&gt;
                  &lt;script src="today/main.js"&gt;&lt;/script&gt;
                  &lt;script src="today/jQuery2.1.1.min.js"&gt;&lt;/script&gt;
  
  
               &lt;/div&gt;
          &lt;/div&gt;
  
          &lt;/div&gt;
  
  
          &lt;?php }else{ ?&gt;
  
          &lt;div class="tech"&gt;
          &lt;header&gt;
             &lt;h1&gt;Header&lt;/h1&gt;
          &lt;/header&gt;
          &lt;div class="main"&gt;
          &lt;div class="panel-heading" style="background: #fff;color: #555;border: 0px;
          border-bottom: 1px solid #ccc;"&gt;
          &lt;h3 class="panel-title" style="margin:10px 0; padding-left:10px;font-weight:bold;    font-size: 18px;"&gt;
          &lt;i style="float:left;padding: 1px 6px 0 0;font-size: 16px;" class="fa fa-sign-in"&gt;&lt;/i&gt;
                          Sign in&lt;/h3&gt;
                          &lt;/div&gt;
  
          &lt;?php echo !empty($statusMsg)?'&lt;p class="'.$statusMsgType.'"&gt;'.$statusMsg.'&lt;/p&gt;':''; ?&gt;
          &lt;div class="regisFrm"&gt;
              &lt;form action="userAccount.php" method="post" style="padding:10px 10px;"&gt;
                  &lt;input class="form-control" type="email" name="email" placeholder="EMAIL" required=""&gt;
                  &lt;input class="form-control" type="password" name="password" placeholder="PASSWORD" required=""&gt;
                  &lt;div class="send-button"&gt;
                      &lt;input type="submit" name="loginSubmit" value="LOGIN"&gt;
                  &lt;/div&gt;
              &lt;/form&gt;
              &lt;p style="padding-left:10px;"&gt;Don't have an account? &lt;a href="registration.php"&gt;Register&lt;/a&gt;&lt;/p&gt;
          &lt;/div&gt;
          &lt;?php } ?&gt;
      &lt;/div&gt;
      &lt;footer&gt;Copyright &amp;copy; &lt;/footer&gt;
      &lt;/div&gt;
  
      &lt;script&gt;
          function drawOnCanvas(file) {
            var reader = new FileReader();
  
            reader.onload = function (e) {
              var dataURL = e.target.result,
                  c = document.querySelector('canvas'), // see Example 4
                  ctx = c.getContext('2d'),
                  img = new Image();
  
              img.onload = function() {
                c.width = img.width;
                c.height = img.height;
                ctx.drawImage(img, 0, 0);
              };
  
              img.src = dataURL;
            };
  
            reader.readAsDataURL(file);
          }
      &lt;/script&gt;
      &lt;/body&gt;
      &lt;/html&gt;
  </code></pre>
  
  <p><strong>main.js</strong>
  in the above ajax i am doing access webcam video data and want to store data in database.   </p>
  
  <pre><code>    'use strict';
  
      /* globals MediaRecorder */
  
      // Spec is at http://dvcs.w3.org/hg/dap/raw-file/tip/media-stream-capture/RecordingProposal.html
  
      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  
  
      if(getBrowser() == "Chrome"){
          var constraints = {"audio": true, "video": {  "mandatory": {  "minWidth": 640,  "maxWidth": 640, "minHeight": 480,"maxHeight": 480 }, "optional": [] } };//Chrome
      }else if(getBrowser() == "Firefox"){
          var constraints = {audio: true,video: {  width: { min: 640, ideal: 640, max: 640 },  height: { min: 480, ideal: 480, max: 480 }}}; //Firefox
      }
  
      var recBtn = document.querySelector('button#rec');
      var pauseResBtn = document.querySelector('button#pauseRes');
      var stopBtn = document.querySelector('button#stop');
  
      var videoElement = document.querySelector('video');
      var dataElement = document.querySelector('#data');
      var downloadLink = document.querySelector('a#downloadLink');
  
      videoElement.controls = false;
  
      function errorCallback(error){
          console.log('navigator.getUserMedia error: ', error);   
      }
  
      /*
      var mediaSource = new MediaSource();
      mediaSource.addEventListener('sourceopen', handleSourceOpen, false);
      var sourceBuffer;
      */
  
      var mediaRecorder;
      var chunks = [];
      var count = 0;
  
      function startRecording(stream) {
          log('Start recording...');
          if (typeof MediaRecorder.isTypeSupported == 'function'){
              /*
                  MediaRecorder.isTypeSupported is a function announced in https://developers.google.com/web/updates/2016/01/mediarecorder and later introduced in the MediaRecorder API spec http://www.w3.org/TR/mediastream-recording/
              */
              if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9')) {
                var options = {mimeType: 'video/webm;codecs=vp9'};
              } else if (MediaRecorder.isTypeSupported('video/webm;codecs=h264')) {
                var options = {mimeType: 'video/webm;codecs=h264'};
              } else  if (MediaRecorder.isTypeSupported('video/webm;codecs=vp8')) {
                var options = {mimeType: 'video/webm;codecs=vp8'};
              }
              log('Using '+options.mimeType);
              mediaRecorder = new MediaRecorder(stream);
          }else{
              log('Using default codecs for browser');
              mediaRecorder = new MediaRecorder(stream);
          }
  
          pauseResBtn.textContent = "Pause";
  
          mediaRecorder.start(10);
  
          var url = window.URL || window.webkitURL;
          videoElement.src = url ? url.createObjectURL(stream) : stream;
          videoElement.play();
  
          mediaRecorder.ondataavailable = function(e) {
              //log('Data available...');
              //console.log(e.data);
              //console.log(e.data.type);
              //console.log(e);
              chunks.push(e.data);
          };
  
          mediaRecorder.onerror = function(e){
              log('Error: ' + e);
              console.log('Error: ', e);
          };
  
  
          mediaRecorder.onstart = function(){
              log('Started &amp; state = ' + mediaRecorder.state);
          };
  
          mediaRecorder.onstop = function(){
              log('Stopped  &amp; state = ' + mediaRecorder.state);
  
              var blob = new Blob(chunks, {type: "video/webm"});
              chunks = [];
  
              var videoURL = window.URL.createObjectURL(blob);
  
              downloadLink.href = videoURL;
              videoElement.src = videoURL;
              downloadLink.innerHTML = 'Download video file';
  
              var rand =  Math.floor((Math.random() * 10000000));
              var name  = "video_"+rand+".webm" ;
  
              downloadLink.setAttribute( "download", name);
              downloadLink.setAttribute( "name", name);
              loadToServer(blob);
          };
  
          function loadToServer(blob){
          var data = new FormData();
            data.append('file', blob);
          debugger;
            $.ajax({
              url :  "recording.php",
              type: 'POST',
              data:data,
              contentType: false,
              processData: false,
              success: function(data) {
                alert("boa!");
              },    
              error: function() {
                alert("not so boa!");
              }
            });
          }
  
          mediaRecorder.onpause = function(){
              log('Paused &amp; state = ' + mediaRecorder.state);
          }
  
          mediaRecorder.onresume = function(){
              log('Resumed  &amp; state = ' + mediaRecorder.state);
          }
  
          mediaRecorder.onwarning = function(e){
              log('Warning: ' + e);
          };
      }
  
      //function handleSourceOpen(event) {
      //  console.log('MediaSource opened');
      //  sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp9"');
      //  console.log('Source buffer: ', sourceBuffer);
      //}
  
      function onBtnRecordClicked (){
           if (typeof MediaRecorder === 'undefined' || !navigator.getUserMedia) {
              alert('MediaRecorder not supported on your browser, use Firefox 30 or Chrome 49 instead.');
          }else {
              navigator.getUserMedia(constraints, startRecording, errorCallback);
              recBtn.disabled = true;
              pauseResBtn.disabled = false;
              stopBtn.disabled = false;
          }
      }
  
      function onBtnStopClicked(){
          debugger;
          mediaRecorder.stop();
          videoElement.controls = true;
  
          recBtn.disabled = false;
          pauseResBtn.disabled = true;
          stopBtn.disabled = true;
      }
  
      function onPauseResumeClicked(){
          if(pauseResBtn.textContent === "Pause"){
              console.log("pause");
              pauseResBtn.textContent = "Resume";
              mediaRecorder.pause();
              stopBtn.disabled = true;
          }else{
              console.log("resume");
              pauseResBtn.textContent = "Pause";
              mediaRecorder.resume();
              stopBtn.disabled = false;
          }
          recBtn.disabled = true;
          pauseResBtn.disabled = false;
      }
  
  
      function log(message){
          dataElement.innerHTML = dataElement.innerHTML+'&lt;br&gt;'+message ;
      }
  
  
  
      //browser ID
      function getBrowser(){
          var nVer = navigator.appVersion;
          var nAgt = navigator.userAgent;
          var browserName  = navigator.appName;
          var fullVersion  = ''+parseFloat(navigator.appVersion);
          var majorVersion = parseInt(navigator.appVersion,10);
          var nameOffset,verOffset,ix;
  
          // In Opera, the true version is after "Opera" or after "Version"
          if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
           browserName = "Opera";
           fullVersion = nAgt.substring(verOffset+6);
           if ((verOffset=nAgt.indexOf("Version"))!=-1)
             fullVersion = nAgt.substring(verOffset+8);
          }
          // In MSIE, the true version is after "MSIE" in userAgent
          else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
           browserName = "Microsoft Internet Explorer";
           fullVersion = nAgt.substring(verOffset+5);
          }
          // In Chrome, the true version is after "Chrome"
          else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
           browserName = "Chrome";
           fullVersion = nAgt.substring(verOffset+7);
          }
          // In Safari, the true version is after "Safari" or after "Version"
          else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
           browserName = "Safari";
           fullVersion = nAgt.substring(verOffset+7);
           if ((verOffset=nAgt.indexOf("Version"))!=-1)
             fullVersion = nAgt.substring(verOffset+8);
          }
          // In Firefox, the true version is after "Firefox"
          else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
           browserName = "Firefox";
           fullVersion = nAgt.substring(verOffset+8);
          }
          // In most other browsers, "name/version" is at the end of userAgent
          else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) &lt;
                 (verOffset=nAgt.lastIndexOf('/')) )
          {
           browserName = nAgt.substring(nameOffset,verOffset);
           fullVersion = nAgt.substring(verOffset+1);
           if (browserName.toLowerCase()==browserName.toUpperCase()) {
            browserName = navigator.appName;
           }
          }
          // trim the fullVersion string at semicolon/space if present
          if ((ix=fullVersion.indexOf(";"))!=-1)
             fullVersion=fullVersion.substring(0,ix);
          if ((ix=fullVersion.indexOf(" "))!=-1)
             fullVersion=fullVersion.substring(0,ix);
  
          majorVersion = parseInt(''+fullVersion,10);
          if (isNaN(majorVersion)) {
           fullVersion  = ''+parseFloat(navigator.appVersion);
           majorVersion = parseInt(navigator.appVersion,10);
          }
  
  
          return browserName;
      }
  </code></pre>
  
  <p><strong>recording.php</strong></p>
  
  <p>This is my recording.php which is use for ajax in url, this is also a action in which i am try to store data in database behalf of this page.</p>
  
  <pre><code>&lt;?php
  
  if(isset($_POST['submit']))
  {
  $con = mysql_connect('localhost','root','') or die(mysql_error());
  $db = mysql_select_db('registered_users',$con) or die(mysql_error());
  
  $sql= "INSERT INTO recording (video_static.webm) VALUES ('".$_POST['file']."')";
  //echo $sql;
  mysql_query($sql);
  
  header("location: index.php");  //link to redirect page 
  
  }
  
  ?&gt;
  </code></pre>