I've been working on a web interface for iPerf and it's going pretty well. My goal is to have the output of the commands be streamed live on the page. It works for iPerf2 commands but when I run iPerf3, it only shows the output once the entire test is complete.
Based on my research I've done on this site and others, I'm thinking it might have something to do with the buffer. I've been messing around with flushing the buffer at different times or setting the 'fread' length to different values but I can't get it to act the same as regular iperf commands. I think this because instead of running the 'popen' on the iperf command itself, I used popen on a python script that would run the iperf command. This still returned the same issue. It only shows the output on the web page once the entire test is complete.
Here is my code:
phpQ.php
<!DOCTYPE html>
<html>
<body>
<div>
Server Domain/IP Address: <input id="address" type="text"><br>
<input id="run" type="button" value="iPerf"><br><br>
</div>
<div id="result"></div>
<script>
function updateText(address) {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (this.readyState == 3) {
var old_value = document.getElementById("result").innerHTML;
document.getElementById("result").innerHTML = this.responseText;
}
};
if (purpose == 1) {
var url = 'ajaxQ.php?address='+address;
ajax.open('GET', url,true);
ajax.send();
}
}
document.getElementById("run").onclick = function(){
address = document.getElementById("address").value;
purpose = 1;
updateText(address);
}
</script>
</body>
</html>
ajaxQ.php - to see the difference, change "iperf -c" to "iperf3 -c" in the $iperfCmd variable.
<?php
function liveExecuteCommand($cmd,$address)
{
while (# ob_end_flush()); // end all output buffers if any
// tells the user what command is going to run
echo "<pre>Running Command: '".$cmd."'</pre>";
// open the command to run and read output
$proc = popen("$cmd", 'r');
$live_output = "";
$complete_output = "";
while (!feof($proc))
{
# flush();
$live_output = fread($proc,4096);
// adds the live output to the complete output
$complete_output = $complete_output . $live_output;
// prints the live output
echo "<pre>$live_output</pre>";
}
sleep(1);
// close the process
pclose($proc);
echo "<pre>------------------------------------------------------------\nAll Done!</pre>";
}
// this happens if the iPerf button is pressed
if (isset($_GET['address'])) {
$address = $_GET['address'];
$iperfCmd = "iperf -c ".$address." -i 1 -t 5";
liveExecuteCommand($iperfCmd,$address);
}
else{
echo "No post request";
}
?>
FYI, I am running the iperf client on an 'Ubuntu 16.04.2 LTS' CLI server and the iperf server on an 'Ubuntu 16.04 LTS' desktop server.
Thanks for any help!
Related
I am able to run this successfully. I would love to accomplish the same thing with out the use of php. Main goal is to change the value of sel from the json file. Below is my php code and json code. the user.php changes the vaule of sel from the json file when a button is hit.
<?php
$jsonString = file_get_contents('sel.json'); //read contents from json file
$jsondata = json_decode($jsonString, true); //convert string into json array using this function
if(isset($_POST['button1'])) //if button is pressed?
{
$jsondata[0]['sel'] = 1; //initialise data to 1
}
if(isset($_POST['button2'])) //if button is pressed?
{
$jsondata[0]['sel'] = 2; //initialise data to 2
}
if(isset($_POST['button4'])) //if button is pressed?
{
$jsondata[0]['sel'] = 4; //initialise data to 4
}
if(isset($_POST['button6'])) //if button is pressed?
{
$jsondata[0]['sel'] = 6; //initialise data to 6
}
$newJsonString = json_encode($jsondata); //encode data back
file_put_contents('sel.json', $newJsonString); //write into file
?>
<!DOCTYPE html>
<html>
<body>
<p>json testing</p>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
<button name="button1" onclick="placeorder()"> sel1:place order</button>
<button name="button2" onclick="cancleorder()">sel2:cancle order</button>
<button name="button4" onclick="unlockenotdone()">sel4:unlock UV box(notdone)</button>
<button name="button6" onclick="unlockedone()">sel6:unlock UV box(done)</button>
</form>
<p id="ui"></p>
<script>
var x = document.getElementById("ui");
function placeorder() {
console.log(1);
x.innerHTML = "Your Order has been Placed";
clear();
}
function cancleorder(){
var usrResponse=confirm('are you sure you want to cancle the order?');
if(usrResponse==true){
cancleconfirm();//call function ChangState2()
}
}
function cancleconfirm() {
console.log(2);
x.innerHTML = "Your Order has been canceled";
clear();//call function clear()
}
function unlockenotdone(){
var usrResponse=confirm('The sterilization is not done. Do you still want to unlock the book?');
if(usrResponse==true){
console.log(4);
openconfirm();
}
}
function unlockedone()
{
console.log(6);
openconfirm();
}
function openconfirm() {
x.innerHTML = "The UV book is now unlocked";
clear();//call function clear()
}
function clear()
{
setTimeout( function(){x.innerHTML="";}, 5000);
return false;
}
</script>
</body>
</html>
this is the sel.json [{"sel":1}]
Simply javascript can never do this, you must have to use of javaScript as well as php for this scenario..
You need to use XHR
step 1 -> handle file saving process as backend using php code.
step 2 -> make a method for button to hit a xhr code to excecute set1 file code
here we go
step 1
creating file with name savingJson.php
/* This is savingJson.php file */
/* here file saving code to handle */
$data = file_get_contents('php://input');
// define path for file
$file = $_SERVER['DOCUMENT_ROOT'] . '/sel.json';
// Write the contents back to the file
file_put_contents($file, $data);
step 2
calling XHR method on button click to run savingJson.php using javaScript
var jsonData = '[{"sel":1}]'
// calling method on button click
var button = document.getElementbyId("btn_id")
button.onclick = function(){
saveJsonToFile(jsonData)
}
function saveJsonToFile(jsonData) {
var xhr = new XMLHttpRequest();
var url = 'savingJson.php' /*path to savingJson.php file*/
xhr.open("POST", url, true); /* must be use POST for large data*/
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(jsonData);
}
Hope so this will help you,
Happy Coding!
Because of reasons, I have a situation in which I need to use a .js file to call a .bat file, which calls a .ps1 file. It may sound crazy, but yes, I have to launch the .ps1 file this way.
My problem is that, the .js file is hanging after writing a variable number of errors. The number of errors that causes the script to hang changes between scripts, but seems to be consistent within a script.
I have included sanitized scripts below.
Every time I run this particular combo using cscript (cscript c:\temp\test.js "c:\temp\test3.bat"), the script stops after writing "Checking device 10 of 100." to the log file and does not return me to the prompt. If I run the .bat file from the same command prompt, the script runs as expected. If, on line 41 of the .ps1 script, I change the message type from "Error" to "Verbose" (for example), the script runs fine and completes as expected.
It seems that the .js file does not like something about "Write-Error $Message" from the Out-PsLogging function but:
I cannot tell what it doesn't like
I cannot tell why it stops writing errors after (in this case) 10 errors
I have seen this behavior on Windows 10 and Server 2019 (ps 5.1).
Code:
test.js
var wshShell = new ActiveXObject("WScript.Shell");
var cmdLine = WScript.Arguments(0);
var result = {};
result.stdout = "";
result.stderr = "";
result.exitCode = -1;
if (!wshShell) {
WScript.Echo("Can not run command");
}
var oExec;
try {
oExec = wshShell.Exec(cmdLine);
WScript.Echo("Ran the command - " + cmdLine);
WScript.Echo(oExec.Status);
var line;
WScript.Echo("About to start while loop");
while (oExec.Status != 1) {
WScript.Echo(oExec.Status);
while (!oExec.StdOut.AtEndOfStream) {
WScript.Echo("Inside the second while loop");
line = oExec.StdOut.ReadLine();
result.stdout += line + "\n";
WScript.Echo(line + "\n");
WScript.Echo(oExec.StdOut.AtEndOfStream);
}
while (!oExec.StdErr.AtEndOfStream) {
WScript.Echo("Inside the third while loop");
line = oExec.StdErr.ReadLine();
result.stderr += line + "\n";
WScript.Echo(line + "\n");
WScript.Echo(oExec.StdErr.AtEndOfStream);
}
WScript.Sleep(100);
}
}
catch (e) {
WScript.Echo("Unable to run command - " + cmdLine);
WScript.Echo(e);
}
test3.bat
cmd.exe /C Powershell.exe -Command "&{C:\temp\test3.ps1 -Verbose}"
test3.ps1
Function Out-PsLogging {
[CmdletBinding(DefaultParameterSetName = 'SessionOnly')]
param(
[Parameter(Mandatory, ParameterSetName = 'File')]
[System.IO.FileInfo]$LogPath,
[Parameter(Mandatory)]
[string]$Message,
[Parameter(Mandatory)]
[ValidateSet('Info', 'Warning', 'Error', 'Verbose', 'First')]
[string]$MessageType
)
$logType = "LogFile"
Switch ($logType) {
"LogFile" {
Switch ($MessageType) {
"Info" { [System.IO.File]::AppendAllLines([string]$LogPath, [string[]]$Message); Write-Host $Message }
"Warning" { [System.IO.File]::AppendAllLines([string]$LogPath, [string[]]$Message); Write-Warning $Message }
"Error" { [System.IO.File]::AppendAllLines([string]$LogPath, [string[]]$Message); Write-Error $Message }
"Verbose" { [System.IO.File]::AppendAllLines([string]$LogPath, [string[]]$Message); Write-Verbose $Message -Verbose }
"First" { [System.IO.File]::WriteAllLines($LogPath, $Message); Write-Verbose $Message -Verbose }
}
}
}
}
$a = 0
$array = #(1..100)
$LogPath = 'C:\temp\log3.txt'
$message = ("{0}: Beginning {1}." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $myinvocation.MyCommand)
Out-PsLogging -LogPath $LogPath -MessageType First -Message $message
$itGlueConfigsMatchingPolicy = Foreach ($device in $array) {
$a++
$message = ("{0}: Checking device {1} of {2}." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $a, $array.count)
Out-PsLogging -LogPath $LogPath -MessageType Error -Message $message
}; Remove-Variable a -Force
$message = ("{0}: Completed {1}." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $myinvocation.MyCommand)
Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message
Turns out the issue is a bug in wscript: https://groups.google.com/forum/#!topic/microsoft.public.scripting.wsh/kIvQsqxSkSk
I'm new to jquery and ajax. I'm trying to get my first ajax script to work, but it's not working and I need some assistance, please.
I have a php page that is supposed to post to another php page, where the latter will do some processing and get some files to get zipped and download. The user needs to input a starting and ending date, and the second php script will use this information to prepare the data. This functionality works perfectly fine without jquery, but doesn't work when I add jquery.
What do I want to achieve? I want to post in the to the same php page and get the post output in a <div></div> tag.
My first php page contains (downloadPage.php):
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<form action="doDownload.php" method="post" id="dateRangeID">
<input id='time1' class='input' name="datefield1" style="text-align:center;"/>
<input id='time2' class='input' name="datefield2" style="text-align:center;"/>
<input type="submit" value="Download Data" name="submit" id="submitButton">
</form>
<div id="result"></div> <!-- I would like it to post the result here //-->
The second page (doDownload.php),
<div id="content">
<?php
if(isset($_POST['submit']))
{
$dateVal1 = $_POST['datefield1'];
$dateVal2 = $_POST['datefield2'];
if($dateVal1 != $dateVal2)
{
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename="file.zip"');
$fullListOfFiles = $downloadFullTmpFolder.$filesList;
$command = "sudo $ldlib -u myuser /usr/bin/python3 $downloadScriptFile -datadir $gnomeDataDir -time1 $dateVal1C -time2 $dateVal2C -outdir $downloadFullTmpFolder > debug_download.txt 2>&1";
$output = shell_exec($command);
$fp = popen('cat '.$fullListOfFiles.' | sudo -u myuser zip -# -9 - ', 'r');
$bufsize = 1024;
$buff = '';
while( !feof($fp) )
{
$buff = fread($fp, $bufsize);
echo $buff;
}
pclose($fp);
}
else
{
echo("<p>Dates have to be different in order for the download to start.</p>");
}
}
else
{
echo("<p>Error: Page called without submit.</p>");
}
?>
</div>
Finally, the jquery part in downloadPage.php, which if I add it doesn't work anymore (which I'd like to learn how to do right, and I mainly learned from the manual of jquery, the last example in the link)
<script>
/* attach a submit handler to the form */
$("#dateRangeID").submit(
function(event)
{
event.preventDefault();
var $form = $(this),
t1 = $form.find("input[name='datefield1']").val(),
t2 = $form.find("input[name='datefield2']").val(),
subm = $form.find("input[name='submit']").val(),
url = $form.attr('action');
var posting = $.post(url, { datefield1: t1, datefield2: t2, submit: subm} );
/* Put the results in a div */
posting.done(function(data) {
var content = $(data).find('#content'); // <--- So this turns out to be wrong. Right is only $(data);
$("#result").empty().append(content);
});
});
</script>
What is wrong in this? Please assist. Thank you.
If you require any additional information, please ask.
Looking at the obvious, you have:
var content = $(data).find('#content');
where, you're trying to find an element with the ID content in one of the following results:
<p>Dates have to be different in order for the download to start.</p>
or
<p>Error: Page called without submit.</p>
I am trying to make a ajax call and validate a input html field. But, instead of getting simple echo message. I am getting complete source code in responseText.
JavaScript
function checkUsername() {
document.getElementById("username").className = "thinking";
usernameRequest = createRequest();
if (usernameRequest == null)
alert("Unable to create request");
else {
var theName = document.getElementById("username").value;
var username = escape(theName);
var url= "checkName.php?username=" + username;
usernameRequest.onreadystatechange = showUsernameStatus;
usernameRequest.open("GET", url, true);
usernameRequest.send(null);
}
}
function showUsernameStatus() {
alert(usernameRequest.responseText);
if (usernameRequest.readyState == 4)
{
if (usernameRequest.status == 200) {
if (usernameRequest.responseText == "okay") {
document.getElementById("username").className = "approved";
document.getElementById("register").disabled = false;
}
else {
document.getElementById("username").className = "denied";
document.getElementById("username").focus();
document.getElementById("username").select();
document.getElementById("register").disabled = true;
}
}
}
}
checkName.php
<?php
$takenUsernames = array('bill', 'ted');
sleep(2);
if (!in_array($_REQUEST['username'],$takenUsernames )) {
echo 'okay';
} else {
echo 'denied';
?>
Previously, I tried to integrate PHP into tomcat, but I was advice it was not a good practice. TRIAL TO INTEGRATE PHP
What I can make out of this situation is that Tomcat is not parsing PHP file and instead it is returning the source code. I believe there should be a means for me to let tomcat parse php files and send the right response.
I have also tried with simple php code, with one statment <?php echo 'HELLO'; ?> and I still get the source code.
Thanks in advance.
NOTE : I do not know php, I am working an example from HEAD FIRST AJAX
you need to install PHP for Tomcat & set its path to compile it.see the below link for php configuration settings.
http://php-java-bridge.sourceforge.net/doc/tomcat6.php
http://www.studytrails.com/blog/php-on-a-java-app-server-apache-tomcat-using-quercus/
Sorry for the really newbie question, just starting to learn AJAX.
I'd like to understand what exactly in the following causes the divMessage content to change continuously when "myName" text is changed.
1) It would seem that the Javascript function process is constantly "listening", is this normal Javscript behavior, or are there any triggers to call "process" repeatedly?
2) Is it true that any function that we assign to "body onload" will be executed repeatedly? How often is this repeated execution?
3) What if we want a single execution of the function process, how to do this?
4) I'm confused because I'm thinking the body will only load once. But is it because after "body onload" the function "process" is called, and the function process in turn modifies the "body" by changing the divMessage, essentially letting it go thru "body onload" again, then "process" again, etc.. ?
Thanks a lot in advance for your help!
<head>
<script type="text/javascript" src="quickstart.js"></script>
</head>
<body onload='process()'>
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage" />
</body>
Here's quickstart.js processing parts
function process()
{
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
// retrieve the name typed by the user on the form
name = encodeURIComponent(
document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send(null);
}
}
// callback function executed when a message is received from the server
function handleServerResponse()
{
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4)
{
// status of 200 indicates the transaction completed successfully
if (xmlHttp.status == 200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
helloMessage = xmlDocumentElement.firstChild.data;
// display the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage+ '</i>';
}
}
}
and the quickstart.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<response>';
$name = $_GET['name'];
// generate output depending on the user name received from client
$userNames = array('YODA', 'AUDRA', 'BOGDAN', 'CRISTIAN');
if (in_array(strtoupper($name), $userNames))
echo 'Hello, master ' . htmlentities($name) . '!';
else if (trim($name) == '')
echo 'Stranger, please tell me your name!';
else
echo htmlentities($name) . ', I don't know you!';
echo '</response>';
?>
Found the answer by shutting down and trying to run this again.
It turns out there was additional code that I commented out
but was cached that calls "process" every 1 second from handleServerResponse():
// display the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage+ '</i>';
setTimeout('process()', 1000);
Sorry about that. Lesson is to clear the browser cache before testing each code change :)
So I guess the advice to check if this function is called from any other place is correct.
Anyway, I read a great deal and learned a lot while trying to figure
this out. Thanks a lot #pst!