Chat update if a new entry in the database - javascript

So i have a problem. A made a chat with php and mysql. But, if I enter a text, I can't see it in the other window because it is not updating. So I started to make a program with iframe, and i found it much cooler than the other. I'm using to reload the frame all 2 seconds. Now my question is, how can I make this easier with javascript, so that the chat is updating automatically?
Code of the frame (I'm german, so it's a little bit confusing):
<?php
require 'config.php';
session_start();
?><head><link href="https://fonts.googleapis.com/css? family=Source+Sans+Pro:300,400,700" rel="stylesheet">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Studit</title><link rel="stylesheet" href="lobby.css"><meta http-equiv="refresh" content="5; URL=/ownwebsite/lobby1embed.php"></head><?php
$abfrage = "SELECT * FROM lobby1 ORDER BY id DESC";
$abfrage_antwort=mysqli_query($con, $abfrage);
if (!$abfrage_antwort)
{
die('Ungültige Abfrage:' .mysqli_error());
}
echo '<table border="1">';
while ($zeile = mysqli_fetch_array($abfrage_antwort, MYSQLI_ASSOC))
{ //row algorithm...}

You can use setInterval (functionRefreshingChat, 1000); in javascript.
It'll create infinite loop with delay 1000ms.
According to one of comments to your question: setTimeout is not solution. It'll execute inner function only once.

Related

Having issues using js to randomly reassign a css variable

I'm working on a part of a page that should load a random image from a folder every fraction of a second for a rapid shuffle. I've gotten it to get the file name and randomly set a style for it. Problem is, not at all how I was intending to do so. I want to set the css variable "--background-images" in my stylesheet, however all it seems to be doing upon manually running the function in console is adjust the html doc like so:
<html lang="en" style="--background-images\::url(\.\.\/\.\.\/rsrc\/acct-crt-page-images\/acct-crt-street-mural-16\.png);"><head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Account - Page 37</title>
<script src="../scripts/script.js"></script>
<link rel="stylesheet" href="../styles/account-creation-style.css" type="text/css">
</head>
Obviously this isn't what I was aiming to change--and beyond that I have no idea what that url it inserted is as it looks like a nightmare. I'm aiming to replace only the line in the css file. This is my js code:
// Load the root CSS variables
const style_root = document.querySelector(':root')
function random_image() {
// Get a random index postion of the images array
array_index = Math.floor(Math.random() * 19)++;
// Change the --background-images css variable based on the random index
style_root.style.setProperty(`--background-images`, `url(../../rsrc/acct-crt-page-images/acct-crt-street-mural-${array_index}.png)`);
}
I don't really know where to start or what is happening here now--I've been working with this aspect of the website for almost a week, and I was getting close but this roadblock has had me for 2-3 days.
I'm attempting to change a line of css, but instead I've gotten a weird and confusing line that doesn't function in html.

Scraping a messy javascript-heavy website with python

I was trying to scrape the household links from this page :
https://www.sreality.cz/en/search/to-rent/apartments?page=2
For instance, for the first apartment I would like to obtain the link with:
https://www.sreality.cz/en/detail/lease/flat/1+kt/plzen-jizni-predmesti-technicka/25873756#img=0&fullscreen=false
However the website is quite heavy on javascript. By using requests.get() I only obtain an uninformative chunk of html code:
from requests import get
i = 2
url = f"https://www.sreality.cz/en/search/to-rent/apartments?page={i}"
response = get(url)
print(response.text)
-----------------------------
<!doctype html>
<html lang="{{ html.lang }}" ng-app="sreality" ng-controller="MainCtrl">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1.0,minimal-ui">
<!--- Nastaveni meta pres JS a ne pres Angular, aby byla nastavena default hodnota pro agenty co nezvladaji PhantomJS --->
<title ng:bind-template="{{metaSeo.title}}">Sreality.cz ⢠reality a nemovitosti z celé ÄR</title>
<meta name="description" content="NejvÄtší nabídka nemovitostí v ÄR. Nabízíme byty, domy, novostavby, nebytové prostory, pozemky a další reality k prodeji i pronájmu. Sreality.cz">
<meta property="og:title" content="Sreality.cz ⢠reality a nemovitosti z celé ÄR">
<meta property="og:type" content="website">
<meta property="og:image" content="https://www.sreality.cz/img/sreality-logo-og.png">
-----------------------------
ETC ...
The question is therefore, how to proceed with some simple scraping activity for websites of this kind ?
Thanks in advance for the help.
I don't think that website has a public API but looking at the API calls from the network tab I could fetch the details for your need and make it as link have a look at the below code.
Let me know if you have any questions :)
import time
import requests
page=2
numberofresults=20
epochmiliseconds=round(time.time() * 1000)
paramsdict={
"category_main_cb":1,
"category_type_cb":2,
"page":page,
"per_page":numberofresults,
"tms":epochmiliseconds
}
data=requests.get("https://www.sreality.cz/api/en/v2/estates",params=paramsdict).json()
for lead in data["_embedded"]["estates"]:
locality=lead["seo"]["locality"]
name=lead["name"]
hash_id=lead["hash_id"]
typedata=[s for s in name.split(" ") if "+" in s][0].replace("\u00a0"," ").split(" ")[0]
print(f'https://www.sreality.cz/en/detail/lease/flat/{typedata}/{locality}/{hash_id}'))
Output:
First ask website, if they provide any API to get the desired information.
To deal with javascript during the scraping only request will not work. You should go Selenium only or for scrapy in combination of scrapy-selenium. These two allow loading of javascript during scraping.
Feel free to ask if you have any other question.

How to quickly send the content of a text file to a mysql database

Hi everyone!
I've made a MySQL database that contains the state of a minecraft lever using the ComputerCraft mod and some javascript but here is the problem : it's too slow :/So I would like to know if there isn't a simpler / quicker way to do it '\(*-*)/`
Here are the steps I went through :1-I've set a computer in my minecraft world with this startup program :
ecran = peripheral.find("monitor")
term.redirect(ecran)
while true do
term.clear()
local h = fs.open("test","w")
print(os.version())
print(rs.getInput("right"))
text = "etatBout = '"..tostring(rs.getInput("right")).."'"
h.write(text)
h.close()
os.sleep(0.5)
term.setCursorPos(1,1)
end
so that the computer write the state of the lever in the file 'test'2-I've created a index.html file in the same folder :
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>TestMCJS</title>
<meta http-equiv="refresh" content="0.5" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="test"></script>
<script type="text/javascript">
console.log(etatBout)
if(etatBout=='true'){
window.open('http://192.168.1.47/minecraft/index.php?etatbouton=1', 'jeux');
}else if(etatBout=='false'){
window.open('http://192.168.1.47/minecraft/index.php?etatbouton=0', 'jeux');
}
</script>
</head>
<body>
<h1>Test</h1>
<p></p>
</body>
so it send a php request to a lamp server I run on a virtual machine with the state of the button in parameter3-I've created the index.php with the following code:
<!DOCTYPE html>
<head>
</head>
<body>
<?php
$connexion = new mysqli("localhost","chuck","plouf","mc");
$requete = $connexion->query("INSERT into `etatbouton` (etat) VALUES ('".$_GET['etatbouton']."')");
$requete->close();
$connexion->close();
?>
</body>
Then the state of the button is in my database in the 'etat' column and is related to a 'date' column with the current_timestamp as default value4-Now I just have to read the database in index2.php :
<!DOCTYPE html>
<head>
<meta http-equiv="refresh" content="0.5"/>
</head>
<body>
<?php
$connexion = new mysqli("localhost","chuck","plouf","mc");
$requete = $connexion->query("SELECT `etat` FROM `etatbouton` ORDER BY `date` DESC LIMIT 1");
$ligne = $requete->fetch_assoc();
if($ligne['etat']!= 0){
echo("<h1 style='font-size:5em;color:blue'>ON</h1>");
}else{
echo("<h1 style='font-size:5em;color:red'>OFF</h1>");
}
$requete->close();
$connexion->close();
?>
</body>
And that's it.
I'm proud of me because I'm a newbie but I would like to know if there is a simpler or quicker way to do it because with this set I have to open 3 tabs and one is a pop-up so it is blocked by the browser and it takes approximetly 1 or 2 seconds to update the button state in the browser :/
Hi again
Appenrently I could use LOAD DATA in my first page to avoid the pop-up and make it quicker so thank you.
Bye Bye ,(°0°)/

HTML equivalent of PHP include for JavaScript parts

I'm looking for a Javascript equivalent of a technique I've been using in PHP. That is, to place even the most basic page setup:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
...in a php file like 'doc_start.php' and then start every page in my site with...
<?php require_once('/path/to/doc_start.php); ?>
Now I need to begin a project that's strictly HTML and JS (no PHP) and want a similar way to avoid duplicating basic, common HTML elements. Obviously, I want to do more than this very basic stuff, like import JQuery in every page, link to a common stylesheet, etc. Again, all easy in PHP, but I'm still kind of a newbie in JS.
I've read about HTML5 includes, but can't seem to find anything that addresses what I want to do
In order to import other pages into your current document, you need to use a link tag.
For example....
<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>
This will allow you to reference other html, css or javascript documents into your page without copying and pasting the same code within each page.
https://www.w3schools.com/html/html_links.asp
Javascript and PHP are different languages for very different purposes. But assuming you have some element you don't want to repeat some elements one solution is the following:
Save the HTML elements that you don't want to keep repeating as a string. Then use the .innerHTML property to add elements.
The .innerHTML property stores the mark up of an element as a string.
For example, if we have the following <div>:
<div class="example"> <br> Hello there this is a test! </div>
...and we use .innerHTML:
console.log(document.querySelector(".example").innerHTML);
It will output "<br> Hello there this is a test!".
We can add to the .innerHTML using the += operator. So if you want to add something inside the body it's as simple as:
var something = "some HTML";
document.body.innerHTML += something;
Hope this was what you were looking for!

Php/JS countdown timer then run stuff

Sorry for poor title.
I basically want to start a countdown (5 minutes) if a certain thing reports back witha number. Most of the backend is in PHP but I want to animate to the countdown so the user can see (maybe even with a progress bar eventually). But once the countdown his zero, if the condition is not met I want it to, lets say refresh the page for simplicity.
I'm looking for some guidance in right guidance. Should I:
Run timers seperately in JS and PHP
or
Do something like this Countdown timer built on PHP and jQuery? with a common php file included or something along those lines
Thanks guys.
well if you want a timer triggered by something that reports to the backend when it its over you could just do an ajax request with JQuery. I will try to explain it based on the condition that PHP has to init the counter as you show to us at the example timer.
Add JQuery to your project Download it here
Download JQuery countdown here, also you can read more about the library here
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="./jquery.countdown-2.2.0/jquery.countdown.min.js"></script>
</head>
<body>
<div class="countdown">
<span id="clock"></span>
</div>
<script>
function initTimer()
{
<?php
date_default_timezone_set('America/Bogota'); //Your target timezone
$time = new DateTime();
$minutes_to_add = 5;
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
?>
$('#clock').countdown('<?php echo $time->format('Y-m-d H:i:s'); ?>')//so we init the timer at te server time + 5 minutes
.on('update.countdown', function(event) {
var format = '%H:%M:%S';
$(this).html(event.strftime(format));
})
.on('finish.countdown', function(event) {
$(this).html('This offer has expired!')
.parent().addClass('disabled');
//at the end of the timer we will send data to the server
$.ajax({
url: "your_server_service_url",
method: "GET",
data: {"some":"data you want to sent to server"}
}).done(function(r){ // r is the response from your server (all text printed)
location.reload(); //After the server get the data we reload the current page.
});
});
}
initTimer();
</script>
</body>
</html>

Categories