I am trying to create a logger window for my website that streams python logger messages to a javascript popup window. I've gotten to the point where if I close the window and reopen it new messages will be displayed, but I want to write some javascript that automatically refreshes the window (and calls dajaxice) every N seconds.
My ajax.py:
#dajaxice_register(method='GET')
def getLogs(request):
fname = "/path/to/LOG_2015-07-08.log"
with open(fname,"r") as f:
lines = f.readlines()
lines = lines[-15:] //
logger.info("Displaying Logs")
return json.dumps({'message':lines})
My html:
<script language="javascript" type="text/javascript">
function popitup(data) {
sessionStorage.setItem("logs",data.message);
newWindow = window.open('/InterfaceApp/LogViewer', 'Log Viewer', 'height=400,width=800,status=yes');
if(newWindow && !newWindow.closed){
newWindow.location.reload(true); //this is my first attempt at a refresh, wasn't quite what I wanted.
newWindow.focus();
}
}
</script>
<div class="container">
<input id="LogMessages" type="button" value="View Log Messages" onclick="Dajaxice.InterfaceApp.getLogs(popitup)"/>
</div>
To reiterate, I want to click the button and have a popup window come up. I want that popup window to refresh every N seconds with the last 15 lines of my log file (the lines are added to the log every time the user navigates around the website). The dajaxice function in ajax.py is what grabs the log files so that somehow call somehow needs to be included in the refresh.
Can anyone help me out with this? I've been struggling with it for days.
Thanks!!
I was able to figure it out on my own. Code below worked for me.
ajax.py:
#dajaxice_register(method='GET')
def getLogs(request):
fname = "/path/to/LOG_2015-07-09.log"
with open(fname,"r") as f:
lines = f.readlines()
lines = lines[-15:]
return json.dumps({'message':lines})
html:
<div class="container-fluid">
<h4 class="text-center">Log Messages</h4>
<div class="content">
<span class='value'></span>
</div>
<script language="javascript" type="text/javascript">
function saveLogs(data){
sessionStorage.setItem("logs",data.message);
}
$(document).ready(
function() {
setInterval(function() {
Dajaxice.InterfaceApp.getLogs(saveLogs);
var logs = sessionStorage.getItem("logs");
document.querySelector('.content .value').innerText = logs;
}, 3000);
});
</script>
</div>
I used dajaxice instead of straight ajax, which took quite a bit of fiddling with before all of the settings were configured correctly, but it seemed easier than trying to learn how to integrate ajax and php into my django project.
Related
A friend and I are newbies to Python, JavaScript, Flask, and D3. We have a website where we get a location name from a user, get the Lat/Lon from one API, then get weather info for that Lat/Lon from a second API using Python functions.
https://laurinalastella.pythonanywhere.com/
Currently, we use a button to generate a link from the input, which opens a second page to display the graphs.
Can anyone suggest a way to make these events happen on the same page? If we could have one button that sent the input to the Python functions, and also loaded the graphs onto the page, that would be ideal.
(I'm also looking into Plotly Dash, but I'm trying to keep this free/affordable.)
Thanks!
Snippets from the HTML file for the home page:
<head>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<!-------------------------
<button id="get_links" class="button1">Generate Link</button>
<!-------------------------
<a id="history_link">Go to Weather History JSON</a>
<!-------------------------
<script type="text/javascript">
var the_button = d3.select("#get_links");
var history_link_thing = d3.select("#history_link");
// the function that fills urls
the_button.on("click", function() {
var urrl = location_val;
history_link_thing.attr("href", "pretty/v1.0/history_loc/"+urrl );
});
</script>`
i'm trying to automate a login and logout script using javascript, but whenever it logs in, the console code clears up. is there a way to make it run thesame script after login? so that it will be able to logout automatically?
this script logs in but after login, it clears the console so it doesn't see the logout code:
var login= document.querySelector("button[type='submit']");
login.click();
var logout = document.querySelector("a[href='https://example.com/logout.php']");
logout.click();
console always refresh when you move page. so i think it's impossible to do it. if you want to make auto login system. maybe selenium or electron are the best way to make it.
here is the link that can help.
#selenium use python :
https://www.selenium.dev/
#electron use nodejs :
https://www.electronjs.org/
I know you wanted to run function on next page, but, anyways, here's what you could do if you stay on the same page:
function login() {
document.getElementById("bye").style.display="none";
document.getElementById("login").style.display="none";
document.getElementById("content").style.display="";
document.getElementById("logout").style.display="";
}
function logout() {
document.getElementById("bye").style.display="";
document.getElementById("login").style.display="";
document.getElementById("content").style.display="none";
document.getElementById("logout").style.display="none";
}
<div id="bye" style="display:none">Bye!</div>
<div id="login"><button id="loginBtn" onclick="login()">Login</button></div>
<div id="content" style="display:none">content</div>
<div id="logout" style="display:none"><button id="logoutBtn" onclick="logout()">Logout</button></div>
I'm trying to create a roulette system, which should work as follows: The user clicks on a submit button, which is then checked on the opening_case_handler.php file to see whether the user has sufficient funds in his account or not, and if he does it will echo javascript code which will create the animation for the roulette and will also come out with the winning prize. For security purposes I am executing the js code in php so the user has no access to it since it is executed in the server side.
The issue here is that the js and jquery code do not get executed once this line of code has been reached:
var gw = $(".gift").outerWidth(true);
in the opening_case_handler.php.
You will notice that there are two alerts before and after the previous line code I have just mentioned. If I uncomment alert("TEST1") it will get executed and an alert message will appear however the rest of the code will no be executed. Also if I uncomment only the alert("TEST2") it will not be executed and nothing will happen.
To make sure that the javascript code actually works. I previously tested it in a javascript file and sourced it in the index.php file and it worked perfectly.
index.php
This page contains the roulette with all the different images of each item. The submit button is at the bottom. This is the button that users will click to be able to spin the roulette.
<div class='rafflebox'>
<div class='pointer'></div>
<div class='boxwrapper'>
<ul class='giftwrapper'>
<div class="gift item bg-size2 box-bg3">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
<div class="gift item bg-size2 box-bg2">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
<div class="gift item bg-size2 box-bg3">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
<div class="gift item bg-size2 box-bg4">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
</ul>
</div>
</div>
<form method="post">
<button type="submit" name="opening_case" class="btn open-box-btn btn-openbox-font button"><img id="lock" src="graphics/iconos/Candado Cerrado Black.png">ABRIR CAJA</button>
</form>
</div>
opening_case_handler.php
<?php
session_start ();
if(isset($_POST['opening_case']))
{
opening_case ();
}
function opening_case ()
{
if ($_SESSION['balance'] >= $_SESSION['box price'])
{
echo '
<script>
//alert("TEST1");
var giftamount = 10;
var gw = $(".gift").outerWidth(true);
//alert("TEST2");
var giftcenter = gw/2;
var cycle = 7;
var containercenter = $(".boxwrapper").outerWidth(true)/2;
for(var i = 0; i <=5; i++)
{
var giftduplicate = $(".giftwrapper").children().clone(true,true);
$(".giftwrapper").append(giftduplicate);
}
$(".button").click(function()
{
alert("You DO have sufficient funds");
var btn = $(this);
btn.hide();
var randomgift = Math.floor(Math.random() * 4) + 1;
var dev = Math.random()*(giftcenter+1);
var distance = giftamount * cycle * gw + (randomgift*gw) - containercenter -24 +dev;
console.log(distance);
$( ".giftwrapper" ).css({left: "0"});
$(".giftwrapper").animate({left: "-="+distance},10000,function()
{
alert("You Won Gift" + randomgift);
btn.show();
});
});
</script>';
} else {
//to be done
}
}
?>
Please feel free to express your ideas on how this type of system should be better built. I am open to all suggestions, I am fairly new to this.
Thank you!!
Try using Heredoc string quoting example for printing your JavaScript:
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
Heredoc text behaves just like a double-quoted string, without the
double quotes. This means that quotes in a heredoc do not need to be
escaped, but the escape codes listed above can still be used.
Variables are expanded, but the same care must be taken when
expressing complex variables inside a heredoc as with strings.
If it is just a php code file. You can try some below.
<?php
echo "some stuff here"
if ($condition){ ?>
<script>
alert("condition true");
</script>
<?php } else { ?>
<script>
alert("condition false");
</script>
<?php }?>
When a form gets submitted it redirects you to the PHP page (ie when you click submit in index.php you will get redirected to opening_case_handler.php ) and then the PHP page will send you back to the index page with the new info. Thus, your javascript code gets printed in the opening_case_handler.php which is why your javascript did not get executed. Also, your javascript code will always be visible unless if you do something really creative so if you are trying to handle any sensitive information do it in PHP or any backend framework you are using.
There are ways to fix this issue but I would recommend a different approach to solve this issue. You can use an AJAX request which basically works in the following manner:
You send a request to your PHP server with the data you want to send.
Your PHP server will process the request and send it back to you
Your Javascript code will process the result and show the animations
or whatever you want to do.
This way your algorithm is not shown and your client ( the javascript side ) only handles information entered by the user and the results came from the server.
In your case, we can do that using the following changes
Index.php (which can be changed to index.html now)
<button type="submit" id="opening_case" name="opening_case" class="btn open-box-btn btn-openbox-font button"><img id="lock" src="graphics/iconos/Candado Cerrado Black.png">ABRIR CAJA</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#opening_case").on("click", ()=>{
// $.get( "opening_case_handler.php?opening_case=true", function( data ) {
// console.log(data.funds)
// });
$.ajax({
url: "opening_case_handler.php?opening_case=true",
success: (data)=>{
if(data.funds) {
alert("You DO have sufficient funds")
} else {
("You don't have sufficient funds")
}
},
dataType: "JSON"
});
})
</script>
opening_case_handler.php
<?php
if(isset($_GET['opening_case'])) {
$result = [
"funds" => true,
];
$ResultsInJSON= json_encode($result);
echo $ResultsInJSON;
}
?>
The index.php will send the request when the button is clicked using AJAX which you can read about it here https://api.jquery.com/jquery.get/ then your PHP will receive the request and response with a JSON code which can be processed using the data.whatever as shown in the example above.
Note: I am not a PHP expert but I believe this will be a better method to use in this case.
Note2: You don't need Jquery for Ajax but it's easier! Here is how you do it without Jquery https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
I am very new to web design and I am trying to get my javascript function and jquery to work. i have been trying to figure this out for a few days. with the function, I cant see why it wont work:
this is in my js file
function myFunction() {
document.getElementById("sign").innerHTML=
"Thank you for signing up!";,
document.getElementById("sign").innerHTML=
"I look forward to speaking with you soon";
}
this is in my html file
<button onclick="myFunction()">Sign Up</button>
<p id="sign"></p>
Here is the jQuery:
$("div:hidden:first").fadeIn(1000).delay(4000).slideUp(1000);
Have I written something wrong? Neither of these react.
I don't know exactly what's broken with your code,
wrapping the script tag in the bottom of your body should make all work well.
HTML:
<button onclick="myFunction()">Sign Up</button>
<div>
<p id="sign"></p>
</div>
JavaScript + jQuery:
var myFunction = function() {
let message = document.querySelector("#sign")
message.innerHTML = "Thank you for signing up!";
$("div:hidden").fadeIn(1000).delay(4000).slideUp(1000);
}
Is that what you wanted to achieve?
To make the message change, I think you have to use setTimeout so it changes/adds after few seconds...
Thanks for every bit of help that you have all rendered in this forum.
On behalf of others, I am grateful and want to make you understand that.
Meanwhile, there is this quest that I need to get solved.
Setting a timeout on an alert box.
That is,
<?php
echo '
<script type="text/javascript">
var t = setTimeOut(5000); //5secs
alert("Your score is: ". $score. '.");
if(t === TRUE){
//clear alert box
this.alert.OK = true;
window.location = "index.php";
}
</script> ';
?>
Please do not mind my psudo-code. It's just my wrongest way of understanding javascript to work.
I know that everything is possible - there could be some way of getting around a challenge. But I do not really have the actual solution. And I am throwing it open to the gurus in the house.
Thanks in anticipation that we will all get through this challenge together.
I remain your loyal friend.
You can't time out an alert. It's a low-level JavaScript construct that creates a native application dialog that needs to be confirmed by the user before it gets destroyed. If you want to "throw up data" to the user, you'll have to use an actual HTML dialog library (or roll your own).
Also, don't use alert(). It was great when we had no alternative, but these days you use console.log(...) to simply log data (any data. numbers and strings, but also entire objects and HTML elements!) to the dev tools console (every browser comes with one baked in), and there are a million and one JS libraries that will generate nice looking modals for users instead (the only legitimate use of an alert these days is to force a halt on the entire page processing thread... And off the top of my head I can't think of a single reason why you'd want to do that).
That said, the PHP code you gave makes absolute no sense at all. It's literally a .js file, with a .php extension. Remove those php tags, save it as .js, and just <script src="thatfile.js"></script> that thing. Don't make PHP do things that you don't need PHP for in the slightest.
Browsers won't allow timeout on their alert, at-least as of now it is not possible. But here is possible way around. Create a message box with html and css.
php:
<?
... what required to compute/fetch the score
?>
<html>
<head>
<meta http-equiv="refresh" content="5;index.php"/><!-- redirect after 5 secs -->
</head>
<body>
<div class="message-box">
<label>Your score is:<?$score?></label>
</div>
</body>
</html>
The meta tag will tell the browser to redirect to the given page after 5 seconds. Mean while the page is displayed to the user with dynamic score given by the php variable.
EDIT: In case if you are not allowed to use meta tags then try this
<?
... what required to compute/fetch the score
?>
<html>
<body>
<div class="message-box">
<label>Your score is:<?$score?></label>
</div>
</body>
<!-- not a good practice to put tag here, but it will do the trick to redirect after page is loaded-->
<script>
setTimeout(function(){
location.assign("index.php");//<-- where to redirect
}, 5000); //<-- redirect after 5 secs
</script>
</html>
is it not possible to do:
var t = setTimeOut(function(){
alert("Your score is: ". $score. '.");
},5000); //5secs
?