I have 2 fetch functions calling the same PHP Script. The whole content of the PHP-Script is the following:
<?php
session_write_close();
sleep(10);
session_write_close(); is only there to make sure the Session is really closed. However the first Script finishes after ~10 Seconds and the second Script after ~20 Seconds:
Why is Script 1 blocking Script 2?
For the sake of completeness here is the JavaScript:
async function test() {
fetch('api/v1/test')
fetch('api/v1/test')
}
test();
For everyone else who faces the same problem: If you develop locally on the Built-In web server you need the following setting: PHP_CLI_SERVER_WORKERS
Windows is currently not supported and PHP >=7.4 is needed.
Link to the documentation: Documentation
As per the comment above, I am unable to replicate the blocking behaviour you mention.
Using essentially the same function and sending a minimal GET request to the PHP endpoint (in this case the same page ) that does essentially the same as the original the requests all return content almost together.
<?php
$t=10;
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['task'], $_GET['seq'], $_GET['func'] ) && $_GET['task']=='test' ){
session_write_close();
sleep( $t );
exit( 'ok: sequence: ' . $_GET['seq'] . ' func: ' . $_GET['func'] . ' date: ' . date( DATE_ATOM ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Blocking or not-blocking?</title>
</head>
<body>
<div id='results'><div>
<script>
const callback=(r)=>{
document.getElementById('results').innerHTML += `${r}<br />`;
}
const test=()=>{
fetch('?task=test&seq=1&func=1')
.then(r=>r.text())
.then(callback);
fetch('?task=test&seq=2&func=1')
.then(r=>r.text())
.then(callback);
};
async function test2() {
fetch('?task=test&seq=1&func=2')
.then(r=>r.text())
.then(callback);
fetch('?task=test&seq=2&func=2')
.then(r=>r.text())
.then(callback);
}
callback(`Begin Tests: ${new Date()}`);
test();
test2();
</script>
</body>
</html>
This yields, for example:
Begin Tests: Thu Feb 09 2023 12:18:59 GMT+0000 (Greenwich Mean Time)
ok: sequence: 1 func: 1 date: 2023-02-09T12:19:09+00:00
ok: sequence: 2 func: 1 date: 2023-02-09T12:19:09+00:00
ok: sequence: 1 func: 2 date: 2023-02-09T12:19:09+00:00
ok: sequence: 2 func: 2 date: 2023-02-09T12:19:09+00:00
Related
This is the HTML code for my Alexa Skill.
<head>
<script src="https://cdn.html.games.alexa.a2z.com/alexa-html/latest/alexa-html.js">
</script >
</head>
<body>
var alexaClient;
Alexa.create({version: '1.0'})
.then((args) => {
const {
alexa,
message
} = args;
alexaClient = alexa;
document.getElementById('debugElement').innerHTML = 'Alexa is ready :)';
})
.catch(error => {
document.getElementById('debugElement').innerHTML = 'Alexa not ready :(';
});
</body>
Works fine on Echo Show 8 and Echo Show 5 but Echo Show 10 gives an error for the same code. It says "Alexa.create is not a function". What can be the possible error?
'Alexa.Presentation.HTML': {u'runtime': {u'maxVersion': u'0.2'}
This is the request for Echo Show 10 Echo show 8 gives version 1.1
Can this be the possible issue?
In the Amazon documents, it's like that:
"device": {
"deviceId": "amzn1.ask.device.XXXX",
"supportedInterfaces": {
"Alexa.Presentation.HTML": {
"runtime": {
"maxVersion": "1.0"
}
},
"Alexa.Presentation.APL": {
"runtime": {
"maxVersion": "1.4"
}
}
}
}
maxVersion is 1.0 so it probably supports create function but echo show 10 has a maxVersion 0.2 so it may not support or have the create function. I don't know the specifics yet.
Can you change
'Alexa.Presentation.HTML': {u'runtime': {u'maxVersion': u'0.2'}
to
'Alexa.Presentation.HTML': {u'runtime': {u'maxVersion': u'1.0'}
?
Assuming you use a virtual environment not a real device.
You may want to check Alexa HTML SDK website.
The problem was with maxversion '0.2'. After device update its works fine
I am trying to make a program which counts down over the space of 15 seconds and displays them using PHP and JQuery. I need to be able to automatically load the server's timestamp into the strtotime function and set this to the start point of the timer, and make the end point of the timer 15 seconds after this point, is there any way I can achieve this?
I have tried setting the times specifically and the timer works for counting to 15 seconds after these points, but I need it to set these times relative to the current moment automatically, as I want it to start and stop the timer at certain undecided points in the program as it is running. I have also tried the reference values 'now' and '-15 seconds' - but these seem to stop the timer at '15 seconds remaining' and it does not count down from this point.
timer.php:
<?php
if(true) {
$countdownEnd = strtotime("-15 seconds");
$countdownStart = strtotime("now");
$timeLeft = $countdownEnd - $countdownStart;
if(isset($_POST["type"]) === true && $_POST["type"] == "timerupdate") {
echo ($timeLeft);
}
}
?>
timer.js:
$(function() {
var timerText = $("[timer]");
setInterval(function() {
$.post("timer.php", {type : "timerupdate"}, function(data){
timerText.html(data + " seconds remaining")
});
}, 1000);
});
timer tests.php:
<!DOCTYPE HTML>
<html>
<head>
<script type="application/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="application/javascript" src="timer.js"></script>
</head>
<body>
<?php include("timer.php") ?>
<p timer></p>
</body>
</html>
I expect the output to be a timer which counts down from 15 seconds whenever the starting condition (the if statement at the beginning of timer.php) becomes true.
Any help is really appreciated, thanks :)
If you want to save the timer after reload you need something like a session with a cookie. have a look at https://php.net/manual/en/function.session-start.php
//start a session and make sure there is no output before
session_start();
//maybe you want to check for the requestmethod before you do additional checks
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//your check for timerupdate.
//you dont have to exact bool compare to true the isset it can only return true or false.
if (isset($_POST["type"]) && $_POST["type"] == "timerupdate") {
if (!isset($_SESSION['time'])) $timeLeft = 15;
else $timeLeft = 15 - (time() - $_SESSION['time']);
//output the timer or whatever you want
if ($timeLeft < 0) echo 0;
else echo $timeLeft;
}
}
you have to add settings: withCredentials: true into your ajax call in order to send cookies
Can you check with using date function with time .
My code is as follows -
<div class="huge">
<?php echo date ("g:i:s A"); ?>
</div>
How do i set <div class="huge"> to refresh every second?
Assuming that you need to get the update from the server (noted the PHP code in your original post), there are two things you need to implement:
A Server-Side script (in this case written in PHP) to be requested by the client for fresh data.
A Client-Side javascript to fetch fresh data from the server and update your div.
Let's make an example.
index.php
<html>
<head>
<title>My date updater</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
<div class="huge"><?php echo date ("g:i:s A"); ?></div>
</body>
</html>
Javascript (using jQuery)
setInterval(function(){
$.ajax({
url:'loadData.php'
}).done(
function(data){
$('.huge').html(data);
});
},1000);
loadData.php
<?php echo date ("g:i:s A"); ?>
Initially your page named in this example index.php will load and show the initial date (using a bit of php code inline).
Then the javascript will start to get data from the server (using an ajax request to loadData.php) every second and the div will be updated with the fresh data.
Hope it helps a bit!
P.S: Date and time information can also be fetched using pure javascript code on the client-side, but for some applications the date and time information on the client-side is not reliable enough since it relies on the date and time settings that are set by the client browser.
You could use Ajax, something like this:
If it's just simple text, or simple HTML being loaded then you could use
setInterval(function(){
$("#huge").load("now_playing.php");
...
}, 5000);
You could also use something like:
function reload() {
jQuery.ajax({
url: "fetch_message.php",
type: "POST",
success:function(data){
$('#huge').innerHTML(data);
setTimeout(function(){
reload()
}, 1000);
}
});
This will update the content of the element with id="huge" every second. you don't need any initial php value.
If you need other elements like minutes and seconds of course you can add dt.getMinutes() and dt.getHours() to the string.
<div id="huge"></div>
<script language="javascript">
function refreshSomething(){
var dt = new Date();
document.getElementById('huge').innerHTML = dt.getSeconds();
}
setInterval(function(){
refreshSomething() // this will run after every second
}, 1000);
</script>
This works too -
<script>function getTime(){
var date = new Date();
date.setTime(Date.now());
return (date.getHours() % 12) + ':' + leadingzero(date.getMinutes()) + ':' + leadingzero(date.getSeconds()) + (date.getHours() < 12 ? ' AM' : ' PM'); ;
}
function leadingzero(n) {
return (n < 10) ? ("0" + n) : n;
}
function updateDiv(){
var d = document.document.getElementsByClassName('yourDivClassname')[0];
d.innerHTML = getTime();
}
setInterval(updateDiv, 1000);</script>
I'm currently using this code on my webpage:
<?php
$url = "https://www.toontownrewritten.com/api/invasions";
$data = json_decode(file_get_contents($url));
if (!empty($data->invasions)) {
echo "<h1 style='text-align:center;margin:auto;padding:2px;font-size:16px;font-weight:bold;text-decoration:underline;padding:2px;'>Invasion Tracker</h1>";
$i = 0;
foreach($data->invasions as $title => $inv) {
print "<h3 style='text-align:center;margin:auto;'><b>District:</b> {$title}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Cog:</b> {$inv->type}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Progress:</b> {$inv->progress}
</h3>";
if (count(($data->invasions) > 1)) {
if (end($data->invasions) !== $inv) {
print "<hr>";
} else {
print "<br style='font-size:2px;'>";
}
}
}
} else {
echo "<h1 style='text-align:center;margin:auto;padding:2px;color:darkred;font-weight:bold;'>No invasions!</span>";
}
?>
I'm looking to make it refresh every 10 seconds via AJAX. However, I keep reading you need to make a function, but I'm not sure how I'd do that with the API? Every 10 seconds, that API is being updated, which is why I'd like this to be updated with AJAX every 10 seconds. Currently, I have it so the user has to manually refresh. Any help is appreciated!
You can simply reload the page with the method proposed here
But if you wanna have an AJAX implementation which just refereshes a part of your html nice and tidy, You gonna have to
Almost forget your PHP code
use the following code to implement the request to the url
$.ajax({
url: "https://www.toontownrewritten.com/api/invasions",
})
.done(function( data ) {
if ( console && console.log ) {
console.log( data );
}
});
Make a JS code which would convert the data got in the previous section to a readable html and show it on your page. It should be implemented in the the block where console.log(data) is.
Put that part of code in a setInterval
setInterval(function(){
//$.ajax();
}, 10000);
And be aware that you are gonna go to hell if your request doen't complete in the interval. see this .
I have a better suggestion, again it is same as using setInterval.
setInterval(function () {
if (isActive) return; // so that if any active ajax call is happening, don't go for one more ajax call
isActive = true;
try {
$.ajax("URL", params,function() { isActive = false;//successcallback }, function () {
isActive = false; // error callback
});
} catch (ex) { isActive = false;}
}, 10000);
Your problem is a failure to understand AJAX. Below is a $.post() example.
First let's make the page that you want your Client (the Browser user) to see:
viewed.php
<?php
$out = '';
// you could even do your initial query here, but don't have to
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<style type='text/css'>
#import 'whatever.css';
</style>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='whatever.js'></script>
</head>
<body>
<div id='output'><?php /* if initial query took place */ echo $out; ?></div>
</body>
</html>
Now you need your JavaScript in whatever.js.
$(function(){
function getData(){
$.post('whatever.php', function(data){
// var htm = do a bunch of stuff with the data Object, creating HTML
$('#output').html(htm);
});
}
getData(); // don't need if PHP query takes place on original page load
setInterval(getData, 10000); // query every 10 seconds
});
On whatever.php:
<?php
// $assocArray = run database queries so you can create an Associative Array that can be converted to JSON
echo json_encode($assocArray);
?>
The JSON generated by PHP shows up in the data argument, back in the JavaScript that created your PHP request:
$.post('whatever.php', function(data){
Hi to all I'm beginner in java script I need to make some alert and
shown that when the page want refresh and done some work like
counter=0 or delete a file how can I do this by jquery and java script?
thank!
You can bind refresh event:
window.onbeforeunload = function () {
return 'Post job process not completed yet.';
}
Before page load/refresh:
<head>
alert("hello");
</head>
Within body:
<script>
$count= 0;
while ($count < 10 ) {
$count++;
}
alert("counter increased: " + $count + " times");
</script>