doudansui6650 2019-03-26 21:03
浏览 316

如何在一个页面上获取JS变量值传递回PHP中的另一个页面

I currently have two pages coded in php one page is called upload.php and the other page is called processing.php.

in the processing.php I currently have some Javascript that is ran it’s purpose is to check a log file for a video encoding progress to get the percentage left. this variable is called “progress” (This works fine when using console.log on the processing.php and I can see the incrementing percentage) I need to be able to get this value back to my upload.php page so that I can dynamically update a progress bar with its current value.

I already have one part of the puzzle working and that's to show a progress bar of the file uploading.

I have included some of the JS code on my upload.php and the JS code using in the processing.php page.

One thing that I tried was to have the JS variable inserted into a PHP session variable on the processing.php page, then echo this session variable out on the upload.php.

I have included in my code snippets below my attempt at using sessions.

Upload.php

<?php session_start();?>
<?php 
$formProvider = new VideoDetailsFormProvider($con);
echo $formProvider->createUploadForm();
?>
</div>

<script>



$("form").submit(function() {
  $("#loadingModal").modal("show");    

  var $el = $("#loadingModal");

     $form = $(this);


     uploadVideo($form, $el);
});

function uploadVideo($form, $el){
  var formdata = new FormData($form[0]); //formelement

  var ajax= new XMLHttpRequest();

  ajax.upload.addEventListener("progress", function(event){
    var percent = Math.round(event.loaded /event.total) * 100;

    $el.find('#progressBarUpload').width(percent+'%').html(percent+'%');




    //console.log(percent);
  });

  //progress completed load event

  ajax.addEventListener("load", function(event){
    $el.find('#progressBarUpload').addClass('progress-bar bg-success').html('Upload completed...');


  });

  ajax.addEventListener("error", function(event){
    $el.find('#status').innerhtml = "Upload Failed";


  });

  ajax.addEventListener("abort", function(event){
    $el.find('#status').innerhtml = "Upload Aborted";

  });

  ajax.open("POST", "processing.php");
  ajax.send(formdata);

}


 Please wait. This might take a while.
           <?php echo($_SESSION['convertProgress']);?>
        <div class="progress">
          <div id="progressBarUpload" class="progress-bar" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
        </div>

Processing.php


<?php session_start();
$convertProgressTest = $_SESSION['convertProgress'];
?>
<script>
    var _progress = function(i){
        i++;
        // THIS MUST BE THE PATH OF THE .txt FILE SPECIFIED IN [1] :
        var logfile = 'uploads/videos/logs/output.txt';

        /* (example requires dojo) */

        $.post(logfile).then( function(content){
// AJAX success
                var duration = 0, time = 0, progress = 0;
                var resArr = [];

                // get duration of source
                var matches = (content) ? content.match(/Duration: (.*?), start:/) : [];
                if( matches.length>0 ){
                    var rawDuration = matches[1];
                    // convert rawDuration from 00:00:00.00 to seconds.
                    var ar = rawDuration.split(":").reverse();
                    duration = parseFloat(ar[0]);
                    if (ar[1]) duration += parseInt(ar[1]) * 60;
                    if (ar[2]) duration += parseInt(ar[2]) * 60 * 60;

                    // get the time
                    matches = content.match(/time=(.*?) bitrate/g);
                    console.log( matches );

                    if( matches.length>0 ){
                        var rawTime = matches.pop();
                        // needed if there is more than one match
                        if ($.isArray(rawTime)){
                            rawTime = rawTime.pop().replace('time=','').replace(' bitrate','');
                        } else {
                            rawTime = rawTime.replace('time=','').replace(' bitrate','');
                        }

                        // convert rawTime from 00:00:00.00 to seconds.
                        ar = rawTime.split(":").reverse();
                        time = parseFloat(ar[0]);
                        if (ar[1]) time += parseInt(ar[1]) * 60;
                        if (ar[2]) time += parseInt(ar[2]) * 60 * 60;

                        //calculate the progress
                        progress = Math.round((time/duration) * 100);
                    }

                    resArr['status'] = 200;
                    resArr['duration'] = duration;
                    resArr['current']  = time;
                    resArr['progress'] = progress;

                    console.log(resArr);

                    /* UPDATE YOUR PROGRESSBAR HERE with above values ... */
                  /*  $("#progressBarconvert").width(progress+'%').html(progress+'%');
                    if(progress==100){
                        $("#progressBarconvert").addClass('progress-bar bg-success').html('Conversion Completed...');
                    }*/
                        var convertProgress = progress;

                    if(progress==0 && i>20){
                        //TODO err - giving up after 8 sec. no progress - handle progress errors here
                        console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }');
                        return;
                    } else if(progress<100){

                        setTimeout(function(){ _progress(i); }, 400);
                    }
                } else if( content.indexOf('Permission denied') > -1) {
                    // TODO - err - ffmpeg is not executable ...
                    console.log('{"status":-400, "error":"ffmpeg : Permission denied, either for ffmpeg or upload location ..." }');
                }
            },
            function(err){
// AJAX error
                if(i<20){
                    // retry
                    setTimeout(function(){ _progress(0); }, 400);
                } else {
                    console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }');
                    console.log( err );
                }
                return;
            });

    }
    setTimeout(function(){ _progress(0); }, 800);
</script>


  • 写回答

2条回答 默认 最新

  • dongnigeng1295 2019-03-26 21:43
    关注

    Since you dont want to leave upload.php you have to add return false; right after uploadVideo($form, $el);

    Otherwise you trigger the upload asynchronously and go to progress.php synchronously(which means you leave upload.php)


    You have 3 responsibilities here, so you could do it with 3 files:

    upload.php - display the upload form

    convert.php - do the conversion

    progress.php - get the progress

    In your convert.php you will need to add the line $_SESSION['convertProgress'] = convertProgress;

    In your upload.php you can update your progressbar now by:

    $.ajax('progress.php', function(content) {
        // set element value etc...
    });
    

    As soon as you start the upload the File gets uploaded and converted by convert.php asynchronously. You can now trigger a JS-Timer, which does the above call to progress.php over and over until it reaches 100.

    If you want to be able to do some errorhandling you can use JSON to pass more data back to your upload.php which calls progress.php.

    PHP (example):

    json_encode([
        'progress' => 0,
        'message' => '',
    ]);
    

    JS decode:

    JSON.parse(<content of progress.php>)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号