I have implemented an ajax function successfully
However, I am facing an issue where when using onprogress, I sometimes receive incomplete HTML response and the console displays
Uncaught SyntaxError: Invalid or unexpected token
but the function still continues.
Below is the function in question:
function xhrAJAX ( divID , param2 ) {
var pcache = (Math.floor(Math.random() * 100000000) + 1);
var params = "divID="+encodeURIComponent(divID)+"¶m2="+encodeURIComponent(param2);
var xhr = new XMLHttpRequest(); xhr.open("POST", "/file.php?pcache="+pcache, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onprogress = function(e) { $("#"+divID).html(e.currentTarget.responseText) ; }
xhr.send(params);
}
***** I understand that replacing .onprogress with
xhr.onreadystatechange = function(e) { if (xhr.readyState == 4) { $("#"+divID).html(e.currentTarget.responseText) ; } }
would resolve the console error. However, in some cases, PHP execution may take a long time and I need to show progress.
My installed PHP8 is set up with NGINX without output buffer. Therefore, running
echo 'stuff'; sleep(3); echo '2';
would display 'stuff' first and then '2' after 3 seconds.
PLEASE NOTE: The PHP section mentioned here is not the main concern.
THE MAIN QUESTION: Is there a way to prevent receiving "half returned html" during onprogress (from the JavaScript side)?