Refresh part of my php page with setInterval() - javascript

I have a value on my PHP page and I want to refresh it per second with setInterval().
So I actually know how to refresh values with html etc. But now I want to do the same with php values. Here is my code:
<script>
setInterval(function()
{
<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';
// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);
//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);
//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);
//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);
$formatMachineActive = 'H:i:s';
$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);
?>
},1000);
</script>
Ofc this isn't working since JS and php arent really great together.
and in my table I just simply have:
<table>
<tr>
<td>Activity:</td>
<td><p id='MachineActivity'></p><?php echo $TimeMachineActive; ?></td>
</tr>
</table>
So the problem now is, it's only refreshing when I press f5. But now I want the autorefresh. I know setInterval() worked for html. Is it possible to get this done for php code?

This should work for you:
JS Code:
<script>
setInterval(function()
{
$.ajax({
url: 'value-generation.php',
type: 'get',
success: function(response){
$("#MachineActivity").html(response)
},
});
},1000);
</script>
value-generation.php code:
<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';
// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);
//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);
//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);
//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);
$formatMachineActive = 'H:i:s';
$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);
echo $TimeMachineActive;
?>

This is how you convert php value to javascript value
<script>
setInterval(function(){
<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';
// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);
//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);
//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);
//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);
$formatMachineActive = 'H:i:s';
$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);
?>
var n_val = "<?php echo $TimeMachineActive; ?>";
console.log(n_val);
},1000);
</script>
Change console and give it to your desire.
But does this make the loading time more ? Every second you are calling a remote page and checking ?

When you refresh, PHP returns the whole page again, and it cannot refresh parts of the page. So if you want just part of the page refreshed, you'll need to use iframes.
<body>
<h1>This is my main PHP page</h1>
<iframe src="[url-to-another-php-page-with-only-the-timer]"></iframe>
</body>
And then you'll have to do a separate php page with just the timer value, and serve the html with a meta tag - this meta tag will do the refresh. Meta tag is detailed in this ticket: PHP - auto refreshing page

You need to define setInterval function.
function setInterval($f, $milliseconds)
{
$seconds=(int)$milliseconds/1000;
while(true)
{
$f();
sleep($seconds);
}
}
Now call your set interval function and it should work fine.

As you know, a PHP file will make the server generate a page when you call its URI.
The way you are using your script won't make the server "regenerate" the page and update the values.
Assuming this, you can:
Externalize the php code which is in your setInterval function (ex: update_time_machine.php)
Recall the externalized PHP resource(using IFrame or a request)
Update your page through Jquery/JAVASCRIPT using the PHP script output.
Edit: Mihali's answer sounds the cleanest one.

I'm sure this will work for you
<script>
setTimeout(function(){
location.reload();
},1000); // 1000 milliseconds means 1 seconds.
</script>

Related

Refreshing html via javascript and php

I'm trying to show a notifications counter updated upon javascript.
I have tried to use the following to refresh the html:
At the top of the page declaring the counter value (how many messages user has):
<?php
$nc = notificationCount($user_data['id']);
$ng = $user_data['id'];
if ($nc >= 1){
$nstyle = 'style="display:block;"';
} else {
$nstyle = 'style="display:block;"';
}
?>
Then the standard initial loading of the counter value that works properly:
<li id ="ndiv" class="nav-item pt8" <?php echo $nstyle; ?>><a href="javascript:void(0);" data-toggle="modal" data-target="#myModal" onclick="showUser(<?php echo $ng;?>)">
<i class="fa fa-bell f18 cr"></i><span id ="nc" class="f16 cr"><?php echo $nc;?></span></a>
</li>
In attempt to keep the counter refreshing every 5000 I tried the following, but it does not refresh despite the increase in value taking place.
<script>
function checkNotification() {
console.log(' each 5 second...');
document.getElementById("nc").value = "<?php echo $nc;?>";
}
var myVar = setInterval(checkNotification, 5000);
</script>
A PHP page returns a result to the client. Once the page returns its result, it's done. You can't have a PHP page return a result every so often. But, what you can do is call out to a PHP page (using AJAX) that returns the notification count at regular intervals using setInterval().
let notifications = document.getElementById("notifications");
// This would be a function that calls a .php page to get
// the notification count returned. You could use AJAX
// to make that call.
function simulateServerCode(){
return Math.floor(Math.random() * 100);
}
let timer = setInterval(function(){
notifications.textContent = simulateServerCode();
}, 5000);
<div>You have <span id="notifications"></span> notifications.<div>
You don't need the server side for showing the notifications.
Try this:
JS:
notificationsCount = document.getElementById("notificationsCount");
numberOfNotification = 10; // example
showing = setInterval(function(){
notificationsCount.textContent = numberOfNotificaton;
}, 5000);
HTML:
<h1>
Number of notifications <h1 id="notificationsCount"></h1>
</h1>

Want to Click on a Website Button Programatically

I want to Click on a Website button that are already going on.
For example:
like url: www.google.com..
I want to Click Google Search button programmatically by using any method in PHP, Javascript, Jquery and Ajax.
if Anyone know Solution. Please tell my and provide the source code.
Note: We dn't need to create own button we want to click on a website button by using class and id.
I want to try this..look like this but not success..I want to click Learn HTML button that are show on iframe...in w3school website..
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<iframe src="http://www.w3schools.com" width="800" height="400"></iframe>
<script>
//setInterval(function () {$("#hand_1151079882").click();}, 3000);
function clime(){
setInterval(function () {document.getElementById("#w3-btn").click();}, 3000);
alert();
}
//using javascript
$(document).ready(function () {
$(".cli").on('click', function(event){
$("#w3-btn").trigger('click');
});
});
</script>
<input type="button" class="cli" name="clime" value="submit" onclick="clime()">
you need set id for iframe
var iframe = document.getElementById('w3schools-home');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
innerDoc.getElementsByClassName('w3-btn')[0].click();
[0] is for button Learn HTML, there 19 element have class w3-btn
Tested and Work on w3schools Try it Yourself ยป
IMPORTANT: Make sure that the iframe is on the same domain, otherwise you can't get access to its internals. That would be cross-site scripting.
as Requested, here example PHP for get Element and Recreated to your own sites.
<?php
$url='http://www.w3schools.com/css/default.asp'; // or use $_GET['url']
$scheme=parse_url($url)['scheme'];
$host=parse_url($url)['host'];
$domain=$scheme.'://'.$host;
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT,30);
curl_setopt($ch,CURLOPT_POST, 0);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML(substr(curl_exec($ch), curl_getinfo($ch, CURLINFO_HEADER_SIZE)));
$xpath = new DOMXpath($dom);
$aElement = $xpath->query('//a');
$length = $aElement->length;
$links=array();
for ($i = 0; $i < $length; $i++) {
$element = $aElement->item($i);
if ($element->tagName=='a' && trim($element->textContent)<>'') {
foreach ($element->attributes as $attr) {
$attrName = $attr->nodeName;
$attrVal = $attr->nodeValue;
if($attrName=='href' && str_replace(';','',$attrVal)<>'javascript:void(0)'){
if(substr($attrVal, 0, 1)=='/'){
$links[trim($element->textContent)]=$domain.$attrVal;
}else if(substr($attrVal, 0, 4)=='http'){
$links[trim($element->textContent)]=$attrVal;
}
}
}
}
}
foreach ($links as $key=>$value) {
echo ''.$key.' | ';
}
You can create a javascript function to get URL from iframe and than request AJAX to PHP that have script ABOVE, you can use echo(but need foreach as example from my script) or json_encode to array $links, then reCREATED button from other url/website to your sites.
or just echo to your sites.
My script still need improvement to handle value of attribut href that use '../' or 'foldername/'
just reminder, for get access ELEMENTS on iframe that pointing to different domain is impossible.
You seem to be missing the element with the id w3-btn which gets clicked programmatically.
Also, it seems both of these are doing the same thing ...
function clime(){
setInterval(function () {document.getElementById("#w3-btn").click();}, 3000);
alert();
}
and
$(document).ready(function () {
$(".cli").on('click', function(event){
$("#w3-btn").trigger('click');
});
});
both are trying to click an element with id w3-btn, just in different ways. You only need one of them.
This might help:
<script>
jQuery(function(){
jQuery('#modal').click();
});
</script>
I got this answer from here.

how to use javascript pass value to php or txt file [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
<?php
$myFile = "new.txt";
$fileOpen = fopen($myFile, 'w') or die("can't open file");
$stringData = "total;
fwrite($fileOpen, $stringData);
fclose($fileOpen);
?>
<html>
<head>
<script>
var defaultValue = 5;
var plus = 1;
var max = 100;
var total = defaultValue;
window.setInterval(
function () {
if (total > max){
total = defaultValue;
}
document.getElementById("demo1").innerHTML = total;
total = total + plus;
}, 1000);
</script>
</head>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
</body>
</html>
I need save the total value into txt file, and than read by txt. so that, when i refresh the browser will not re-looping, but how i get value from javascript or from div into php? (read and write per second)
You can use an AJAX request to a php file where you can save it to txt file or a database.
But, making an ajax call every second would be unnecessary traffic. Instead I think using window.onunload would be a better choice, which saves the value when the page is redirected or refrshed.
You can use the jquery bind for that as below:
$(window).bind('beforeunload', function(){
// make ajax call here
});
If you want to save very small amount of data, like here you need to save the value of total then you can use HTML 5 provided local storage which can easily contain on average 5 MB of data. Its nothing but a storage in each domain(origin) which can store 5 MB on any individual client.
It is very easy to use like.
enter code here
// Store
localStorage.totalValueHolder = total;
// Retrieve
var totalStringValue = localStorage.totalValueHolder;
total = parseInt(totalStringValue, 10)
OR
// Store`enter code here`
localStorage.setItem("totalValueHolder ", total);
// Retrieve
var totalStringValue = localStorage.getItem("totalValueHolder");
total = parseInt(totalStringValue, 10)
Hope it will answer your question. If you have further query please let us know.

jQuery $.post() using output data as selector

I am trying to build a quiz environment. The user selects an answer and then clicks submit. Upon submit, the following jquery is called:
$(document).ready(function() {
$('.btn-large').click(function() {
$.post("correct_quiz.php",
{
choices : $('input[name=choice][type=radio]:checked').serialize()
},
function(data) {
var temp = '#correct' + data;
var temp2 = '#correct3';
$(temp).show(); // Make the wrong/right icons visible
});
});
});
This jquery makes a green or red icon appear, based on whether the answer was correct or not. The correct_quiz.php script contains:
<?php
$root = "/users/stadius/maapc/public_html/";
include($root . "connect_to_database.php");
$choices = $_POST['choices']; // This will for example output "choice=3"
echo substr($choices,7,7); // This will then output "3"
?>
I ran into a problem, when I try the above jquery code with variable temp2 the script works like I want. But when I try it with variable temp it doesn't. When I debug, I see that they contain exactly the same string though: both are '#correct3' (when I choose the 3rd answer).
So why is this not working when I use variable temp, and is working when using temp2?
I think your problem is in this line:
echo substr($choices,7,7);
Try to use:
$list = explode('=', $choices);
echo $list[1];
instead of substr

Javascript Variable in Ajax Updater

I am trying to send the javascript variable 'sortlist' to an Ajax function using the following code:
<div id = "output">Drag to sort</div>
<script type="text/javascript">
var session = <? echo $sesh; ?>;
var track = <? echo $trk; ?>;
var sortlist = "sortlist_" + session + "_" + track;
Sortable.create(sortlist,{
onUpdate:function(){
new Ajax.Updater('output','program_sort.php',
{onComplete:function(request){},
parameters:Sortable.serialize(sortlist),
evalScripts:true,
asynchronous:true}
)
}
})
</script>
The variable appears to be passing successfully to Sortable.create (because I can sort the boxes on the webpage), but it does not appear to be passing into Sortable.serialize within Ajax.updater (because it no longer writes the sort order values to the database).
This code works when I use the literal value in Sortable.serialize, like
parameters:Sortable.serialize('sortlist_1_1'),
I have tried using sortlist as a variable with and without single and double quotes inside Sortable.serialize to no avail. What is the format required to successfully pass this variable information?
For reference,
My AJAX/javascript experience is about a 1 (scale 1-10); my PHP/MySQL experience is about a 7 (scale 1-10).
Try this:
Sortable.create(sortlist,{
onUpdate:function(sortlist){return function(){
new Ajax.Updater('output','program_sort.php',
{onComplete:function(request){},
parameters:Sortable.serialize(sortlist),
evalScripts:true,
asynchronous:true}
)
};}(sortlist);
})
Let's go one step further then:
function(sortlist){
Sortable.create(sortlist,{
onUpdate:function(){
new Ajax.Updater('output','program_sort.php',
{onComplete:function(request){},
parameters:Sortable.serialize(sortlist),
evalScripts:true,
asynchronous:true}
)
}
});
}(sortlist);

Categories