How to log PHP file run with jQuery AJAX in browser console?

北慕城南 提交于 2019-12-23 17:15:02

问题


I have a PHP file that does data processing. It's run by $.ajax(), sometimes on big files that take a long time to process. I need to log some info about the ongoing process in the browser console that is displayed on the go, not just when the PHP file has finished running.

From the research I did, I get that there are two difficulties:

  1. Getting PHP to spit out something before it's done
  2. Getting jQuery/JS to display it on the go

To address #1, I've tried:

echo "started"."<br>";

foreach (array("done this", "done that","had a coffee","burp") as $msg) {
    sleep(3);
    echo $msg."<br>";
    flush();
    ob_flush();
}

flush(); ob_flush(); is supposed to do the job, although as you can test here it does not strictly display ever 3s as it's expected to. Any suggestion to get it to display as expected?

As for how to address #2, I have explored a solution involving XMLHttpRequest, but I'm not familiar with the subject so not sure neither what to look for nor if it's the right direction...

Here is the test code of what I'm trying to get to run:

$("#run").click(function(e) {
  $.ajax({
    url: "http://constances-web-dev.vjf.inserm.fr/constances-web/ajax-test.php",
    xhr: function() {
      // get the native XmlHttpRequest object
      var xhr = $.ajaxSettings.xhr();
      xhr.addEventListener('readystatechange', function(e) {
        console.log(e)
      });
      // set the onprogress event handler
      //xhr.onprogress = function(evt){ console.log(evt.target.response) } ;
      // set the onload event handler
      return xhr;
    },
    success: function(msg) {
      console.log(msg);
    },
    error: function(msg) {
      console.log("Erreur: " + msg);
    }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="run">go</button>

Subsidiary question: Is there an (easy) way to go around the cross-origin restriction in order to get an AJAX example to work in a SO snippet?


回答1:


as a work around I've added a log to file to my write2log function

static function log2File($string, $logFileName) {
        if (substr($string,0,1 ) == "\n")
            exec("echo '".date('Y-m-d_H:i:s')." ".addslashes(substr($string,1))."' >> ".$logFileName,$output,$status);
        else
            exec("echo -n ".addslashes($string)."' >> ".$logFileName,$output,$status);
    }

I can then tail -f the log to watch how things are going

but this takes ssh access to the server so i'd still be interested in figuring out how to log to console



来源:https://stackoverflow.com/questions/45863567/how-to-log-php-file-run-with-jquery-ajax-in-browser-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!