setInterval php variable in javascript [duplicate] - javascript

This question already has an answer here:
PHP code only runs once inside javascript setInterval
(1 answer)
Closed 8 years ago.
I am trying to post an updating ping on my website, without having it reloading all the time, yet when i try it posts the initial ping, but it doesnt update after the time interval i've set
index.php :
<script>
setInterval(document.write('<?php echo json_encode(getPingout());?>'),100);
</script>
functions.php :
<?php
function getPingout() {
// some function that finds the ping of the server
return $server->getPing();
}
?>

You can't just have php run multiple times after a page has loaded. That PHP is executed one time when the page loads.
To do what you are attempting to do you should use some javascript and an ajax call.
$(function(){
function pingServer(){
$.post('/ping.php',function(data){
console.log('server is ok');
});
}
setInterval( pingServer, 4000 );
});
Also you may not need to ping the server every that often (every 100). Otherwise you may have issues.

That is not how javascript & PHP work together.
In order to refresh data without a page reload, you must request the data asynchronously. Search for AJAX or XHR, I really recommend that you look into something like jQuery though, as you will save alot of time writing code and debugging, compared to if you were to write the javascript by yourself.
If you were to do this in jQuery:
//this means run when page is ready
$(function(){
setInterval(function(){
//Send POST request to ping.php
$.post('ping.php',{},function(){
//Append the result to the body in a new div
$('body').append($('<div>'+data+'</div>'));
});
},100);
});
and your ping.php should simply return the ping and nothing else.
And don't let the dollarsigns confuse you, in PHP its a prefix for variables, but in the javascript/jquery context it simply is a variable, containing the jquery object that you call functions from.

Related

Pass php var to Javascript from an ajax call

I would create an ajax code that load a php page every x seconds.
Result: obtain a specific php var in the loaded page.
Then: assign the value of the obtained var to a javascript.
Polling, in your case downloading a page every x seconds, is hardly ever the best approach to a problem. It wastes resources.
However, if you want to do something with Ajax, I suggest you use JQuery:
https://api.jquery.com/jquery.get
An example, suppose you have a php 'test.php' file with:
echo $myVariable;
You can then do this in javascript:
$.get("test.php", function( data ) {
alert( "The PHP variable is: "+data);
});
Combine this with a Javascript timer and you're done.

Button On click call jquery function and acess php

I am very new to Wordpress and Woocommerce. I have few doubts wrt jquery in Wordpress. Say i have a function
function test(){
alert("test");
<?php
error_log("Test ---------------------------- ", 0);
?>
}
and a button:
<input type="button" id="btnclick" onclick="test();" value="Test" />`
error log is printing on page load but not on click. But i want to execute code inside php block only when user clicks on button.Is there a way to achieve this ? Thanks in advance`
jPO has already explained how to solve this in a good way, but I thought I should explain why this happens.
PHP is executed on the server. Once the page has been sent to the client, the PHP is no more. JavaScript happends on the client, and can be executed as long as the user is viewing the webpage. Since they do not live during the same timeperiod they are not aware of each other and can not be mixed in that way.
When you visit the page in your browser, the browser sends a request to the server. On the server the PHP interpreter goes through the code of the requested page, executing everything between <? and ?>. It does not understand what the other stuff around it is - it could be HTML, JS, plain text, anything, the PHP interpreter does not know and does not care. That is why it writes to the error log on page load.
When the PHP interpreter is done it has produced a document looking like this:
function test(){
alert("test");
}
That is sent to the client, and the JS (without any instruction to write to the error log) is run on the client when the button is pushed.
Not possible like that. If you'd like to do so. You need something like ajax method in php which you can call. Let's say you have a file in the root of your project called ajax.php, there you can define a function named test(), then you have to have a $_REQUEST translator, which calls your function test(), so the ajax.php would look like this
<?php
// checks if you sent a parameter named method and calls the method
// if you provide parameter named params it will send them too
if(isset($_REQUEST)){
if(isset($_REQUEST["params"]))
ajax($_REQUEST["method"],$_REQUEST["params"]);
else
ajax($_REQUEST["method"]);
}
function ajax($function,$data = null){
$function($data);
}
function test(){
error_log("Test ---------------------------- ",0);
}
and your ajax would look like this
function test(){
$.ajax({
url:"ajax.php",
data:{
method:"test"
}
});
}
hope it helps

PHP automatic logout without having to refresh the page [duplicate]

This question already has answers here:
PHP session timeout script [duplicate]
(4 answers)
Closed 8 years ago.
I am writing a project in PHP, JavaScript and HTML. I have successfully done the automatic logout when the user is idle for 1 minute. But the problem comes in that I have to refresh the page for it to be executed and log me out.
Can somebody help me so that immediately 1 minute is over and the user is idle, the code will be executed and it will take me to the login page without me refreshing it?
Here is my code:
// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
$session_life = time() - $_SESSION['timeout'];
if($session_life > $inactive)
{
echo"<script type='text/javascript'>
window.alert('Your Session got Expired');
</script>";
header("Location: logout.php");
}
}
$_SESSION['timeout'] = time();
//Continuation of other codes
I guess the best way to implement is by using the combination of JS and PHP
check.php
if(isset($_SESSION['timeout']) ) {
$session_life = time() - $_SESSION['timeout'];
if($session_life > $inactive) echo "0";
else echo "1";
}
$_SESSION['timeout'] = time();
.js
$(document).ready(function(){
setTimeout(function(){
$.get("check.php", function(data){
if(data==0) window.location.href="logout.php";
});
},1*60*1000);
});
Or just wrap it in setInterval(function(){},1*60*1000) instead of setTimeout() if you want it to be checked after every one minute.
$(document).ready(function(){
setInterval(function(){
$.get("check.php", function(data){
if(data==0) window.location.href="logout.php";
});
},1*60*1000);
});
You can't do that with php. You need to count time in javascript and make ajax request after that. Simplest way is probably use jQuery plugin like IdleTimeout.
PHP code needs to be called/run to execute... It wont run in the background unless something is running it..
You have a few options:
1: Ajax as suggested by Shikhar.. You have to have something like a setTimeout in javascript which would call this every minute or how ever often
2: A cron job... but a cron job that checks every active session file and if it has expired, then you simply delete it (Kills a session)
3: Have some other means of loading a PHP file as often as you want to check
Even with the above, there is no sure way of doing this..
Cron job / PHP loading.. they need a trigger... and a cron job wont redirect your user the second their session is expired.
Your only choice here is to use ajax on a timer to post to the sever and check if the session is still valid, if not then redirect once the response comes back from PHP to the ajax call.
But even then, once a user has logged in and if they disable JS... you wont get no redirect or checking.
#JOB You need to fire an ajax request something like following
<script type="text/javascript">
jQuery(document).ready(function(){
setInterval(function(){
jQuery.ajax({
url: 'http://localhost/your_script.php',
type: 'POST',
success:function(response){
alert("You are logged out");
return false;
}
});
}, 1000);
});
</script>
This script will check the status of logout after every 1 second and logs out the user if the user is idle for the time decided by PHP script.

How to pass PHP/html to javascript loop

I have a pretty robust JavaScript script that controls my room lights via some external software. I have a PHP that when run returns only a 1 or a 0. I ideally want to have a JavaScript loop that runs every couple seconds and pulls that 1 or 0 and if it is a 1, do some work. Problem is, can't figure out how to get the JavaScript to open another page in terms or processing/data collection.
Is there a "file get contents" equal to JavaScript? I don't want the PHP values written on the JavaScript page, just to have the value to do a little if statement.
As #Marc B said, you want to make AJAX calls. Here is a idea in how to implement it using jQuery.
<script>
function updateData(){
$.get( "ajax/test.html", function( data ) {
//now "data" has the response
});
}
setInterval(updateData, updateInterval);
</script>
JavaScript Timers - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Timers
jQuery $.get() - http://api.jquery.com/jQuery.get/

auto reload: how it works?

i need to change something in my site, if some fields changed in database, but without reloading the page! but i have no idea how i can do it.
could you give me an idea? thanks
example:
for example, i have a forum, and i need to show a image, if new comment resieved! i can write all functions, but i don't understand when i must call the function?
maybe window.onload?
Then you need AJAX!
Explanation:
You need two pages, the main page which does not "reload". And a second one which returns two versions of the small image based on the database field.
Page one has this JavaScript in it:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
/* normal ajax without periodical refresh
$.ajax({
url: 'page2.php',
success: function(data) {
$('#database_status').html(data);
}
});
*/
var refreshId = setInterval(function() {
$('#database_status').load('/path/to/your.php');
}, 3000);
</script>
// Or you use the jQuery plugin Heartbeat: http://www.jasons-toolbox.com/JHeartbeat/
And a div <div id="database_status">empty</div>
The second page, returns a image tag based on the database setting for example in PHP:
<?php
// do db request
if ($request) {
echo '<img src="true.gif"> TRUE';
} else {
echo '<img src="false.gif"> FALSE';
}
Ajax
Once you've familiarized yourself with the concept, you can reference the jQuery AJAX documentation for information on how to implement it with jQuery.
You can use jQuerys load- or JSON-method to get data from your server.
In your case the following scenario is possible:
The site loads.
Your JavaScript loads the initial data from the server.
Now, every couple of seconds or minutes (Depending on your use case), the JavaScript asks the server if anything changed since it last asked (Use timestamps in your request, for example).
If so, change the website accordingly.
Goto 3.
Please keep in mind that excessive polling might but enormous strains on your server, especially if you have a lot of users. Long-polling or Comet are advanced techniques to handle the load.
The easiest way to perform an ajax request with jquery is the load method. On that page you can also see plenty of examples.
There are two basic approaches you can take:
Use setInterval to make an Ajax request periodically that ask the server if there are any updates.
Use Comet to fake server push
Try Ajax, e.g: using jquery which allows you to handle those in a high level js.
example in this site when you do the send email

Categories

Resources