Home > other >  AJAX, PHP, Python : Incremental Data Output
AJAX, PHP, Python : Incremental Data Output

Time:02-10

How to output the data incrementally from a ajax request when php executes a python script with variables? The below code output all the data on completion, my actual python script is large and can take over 10 minutes to complete. I like to see the printed status message embedded into the script. Or is there a is a better way then what I’m trying to attempt.

$('#form').on('click', '.refresh-button', function () {
    var dataString =  'mystring1="test1"'  
                      '&mystring2="test2"';
    $.ajax({
        type: "POST",    
        url: "./php/pyhon_test.php",  
        data: dataString,
        cache: false,
        xhrFields: {
            onprogress: function(e) {
                console.log(e.currentTarget.response);
            }
        },          
        success : function(data) {
            //console.log(data);
        },
        dataFilter : function(data) {
            console.log(data);
        }           
    });
    
    return false;   
}); 

<?php
    session_start();
    session_write_close();
    
    passthru("/bin/python3.9 /python/python_script.py ". $_POST["mystring1"] ." ". $_POST['mystring2']);
    
    //if( ($fp = popen("/bin/python3.9 /python/python_script.py ". $_POST["mystring1"] ." ". $_POST['mystring2'], "r")) ) {
    //  while( !feof($fp) ){
    //      echo fread($fp, 1024);
    //      flush(); // you have to flush buffer
    //  }
    //  fclose($fp);
    //}         
    
    session_destroy();
?>

python_script.py
import sys
import time

mystring1 = sys.argv[1]
mystring2 = sys.argv[2]

print(mystring1 "-a")
time.sleep(2)

print(mystring2 "-b")
time.sleep(2)

print(mystring1 "-c")
time.sleep(2)

print(mystring2 "-d")
time.sleep(2)

print(mystring1 "-e")
time.sleep(2)

print(mystring2 "-f")
time.sleep(2)

xhrFields console.log : test1-a test2-b test1-c test2-d test1-e test2-f

dataFilter console.log : test1-a test2-b test1-c test2-d test1-e test2-f

CodePudding user response:

  •  Tags:  
  • Related