I have this simple function in javascript to refresh a page after a set time.
function AutoRefresh( t ) {
setTimeout("location.reload(true);", t);
}
Now after every refresh, I want it to call a PHP function, for example:
function writeName()
{
echo "Refresh me";
}
Is it possible to call the PHP function in JavaScript after every refresh?
Thanks
I'm afraid the answer is no. By the time JavaScript has been run on your page, the server side (PHP) has already finished processing. Your best bet is to accomplish what you need before the page load, or accomplish it with JavaScript alone.
If you are refreshing the page, you're effectively reloading it from the server, so any 'onload' events will fire again. The page will render again from scratch. You can call a PHP script using AJAX in some 'onload' Javascript listener if you like, though. e.g. with JQuery:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function () {
setTimeout("location.reload(true);", 2000);
$.get('home.html', function(ret){
$('body').html(ret);
});
});
</script>
</head>
<body>
<h1>Test</h1>
</body>
</html>
Beware of calling setTimeout() recursively though as it can make a page unresponsive over time. You may find this useful:
http://www.erichynds.com/javascript/a-recursive-settimeout-pattern/
Related
How to continue run ajax call after redirect to another page in PHP?
How to go from one page to another page when Ajax call is on in PHP?
My ajax call is performing a very complex task and it will take a longtime So, Is it possible to run an ajax call after page redirect?
I make ajax call on submit button click and after that page redirects on another page and then my ajax call is Continue Running in Backend.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title></title>
</head>
<body>
<input type="text" name="altname" id="altname">
<button id="btnSubmit">Submit</button>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','#btnSubmit',function(){
var altname = $("#altname").val();
$.ajax({
url:"http://localhost/z/backend-queue-job-php/queue_job.php",
type:"POST",
data:{altname:altname},
success:function(result)
{
alert(result.msg);
}
});
window.location.href = "http://localhost/z/backend-queue-job-php/thankyoupage.php";
});
});
</script>
The simpler way to run a PHP script in background is with exec or shell_exec
You can run following function in a php file which is called via ajax, passing the path of your current script with a log path if you want to store log info:
shell_exec("/path/to/php /path/to/queue_job.php > /path_to_log/debug.log 2>&1");
It can only be done using async task in your PHP part.
Assign an ID for every task
Your ajax will create new task or fetch the status of existing task
Jquery Mobile auto-refresh every X second
Porting to JQM and having trouble getting page that automatically refreshes content every X seconds to display properly. Have read dozens of related threads but not finding a clear solution with code example. The purpose of this page is to display arrival and departure information on something similar to what you might see in an airport.
Previous approach was as follows with javascript in the header. PHP content (a styled table) would load to named DIV after one second then refresh every ten seconds automatically and worked great:
Controlling Page:
<head>....
<script type="text/javascript">
function Refresh_My_DynamicContent(){
$("#id_My_DynamicContent").load("NewContent.php");
setTimeout(function() { Refresh_My_DynamicContent(); },10000);
}
</script>
<script type="text/javascript">
setTimeout(function() { Refresh_My_DynamicContent(); },1000);
</script>
</head>
<body>
<div data-role="page">
<div id=” id_My_DynamicContent”></div>
</div>
When I use this same approach with JQM the content displays but without JQM, pop-ups all expanded, etc. Could anyone please help direct me to the proper approach with JQM to have a “hands-off” display that refreshes on its own with code example?
I think your code should be like
<script type="text/javascript">
$(function(){
setTimeout(function() {
$("#id_My_DynamicContent").load("NewContent.php",{'reload':true});
},1000);
});
</script>
also check that after the first call is working
I am not sure if jquery moble also relaces the all head if that is the case you should also
echo the js from the PHP
<?php
echo '<script type="text/javascript">
$(function(){
setTimeout(function() {
$("#id_My_DynamicContent").load("NewContent.php",{'reload':true});
},1000);
});
</script>';
?>
Good day guys. So I'm trying to work on this simple jQuery program that triggers a function whenever and only whenever a select value has been changed. I plan to use this simple function in a more complex program once I make it work.
This is the code (it came from jQuery API website, and I modified it slightly to try what I wanted to happen):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>change demo</title>
<style>
div {
color: red;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<select id="selector" name="sweets">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<div></div>
<script>
$( "#selector" )
.on('change',(function () {
$( "select option:selected" ).each(function() {
<?php header("Location:jcue.php")?>
});
})
.change();
</script>
</body>
</html>
What I want to happen is that, the page should only redirect to jque.php once the select input value has been changed. But what's happening in the program is that it automatically redirects to another page without even loading the current page itself. What's the problem? jQuery and Javascript are the unexplored foreign lands for me in web programming, and I know this is pretty basic to many web programmers, but I just need it (and I really have to start learning Javascript, AJAX, and jQuery when I get to have free time haha).
The complex program I'm going to use it to is a search results filtering program. But before I can do that, I have to make this simple program work.
Can anybody help me? Thank you. Answers will be greatly appreciated.
Try this instead::
$(function() {
$("#selector").change(function() {
location.href = "jcue.php";
});
});
This will fix your issue.
The problem is because your PHP gets executed as soon as the page loads - you cannot incorporate it as you have into javascript. Also, you don't need the each() within the handler. Try this instead:
$("#selector").on('change',(function () {
window.location.assign('jcue.php');
});
JavaScript is client-side script, while PHP is server-side. You are trying to trigger a PHP header redirect which should happen at server-time before it's sent to the client's browser. So this will not be working in that on change event.
Simply use:
$("#selector").change(function() {
window.location = "jcue.php"; //this can be URL as well
});
P.S. I noticed you have two "selected" options, mind tell why?
Not so good practice: to redirect using Javascript, since JS can be blocked
There were some syntax errors, here's a fix, just replace your code.
$( "#selector" ).on('change',(function () {
var str = "";
$( "select option:selected" ).each(function() {
window.location.replace("http://stackoverflow.com");
});
}));
Good Practice: use jquery ajax requests Jquery Ajax or redirect using standard php header function(which has to run before your html/js is loaded)
Good luck, learning programming. It's fun!
I want to execute a php code when a user click on a given link , i've tried the following code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("up.php");
return false;
}
</script>
</head>
<body>
<center>
Click Me!
</center>
</body>
</html>
where up.php is a php code that implement android GCM mechanism similer to the one in the link : GCM with PHP (Google Cloud Messaging)
but unfortunately when the link is clicked nothing happens , the php code not executed ,and only the url of the page change form *****.com/test.html to *****.com/test.html# , and by the way I've tested the php code and its works fine so it is not a problem in php code , so what i have missed here? why the code is not executed?
i found the solution , the problem that the jquery library is not included probably in my code
you are using jquery. $.get() will be something like below.
$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
for further help check http://api.jquery.com/jQuery.get/
Sometimes, you may need to call some JavaScript from within a link. Normally, when user click on a link, the browser loads a new page (or refreshes the same page).
This might not always be desirable. For example, you might only want to dynamically update a form field when the user clicks a link.
To prevent the load from refreshing, you could use the JavaScript void() function and pass a parameter of 0 (zero) as below.
<a href="JavaScript:void(0);" onclick="return doSomething(); " />Click Me!</a>
Now if you want to use href="#", make sure onclick always contains return false; at the end.
OR
Use href="javascript:void(0)"
You can also use jQuery Load
function doSomething() {
$('#result').load('up.php', function() {
alert('Load was performed.');
});
}
When you are using Jquery should be :
function doSomething(){
$.get('up.php', function(data) {
$('.data').html(data);
});
}
Link
To stop page refreshing, you can use the javascript void() function and pass parameter of 0.
Click Me!
<div class="data"></div>
This div is used to display up.php result.
Ok start of by using fire bug and watch the console and network panels
Ensure the browser is trying to get something and not returning a 404 or a php error on the get
Look into prevent default http://api.jquery.com/event.preventDefault/
To stop the original link functionality working
If you still want them to move to the link use a window location or...
Look into bootstrap link buttons
http://twitter.github.com/bootstrap/base-css.html#buttons
( the link button )
hi i need to validate the next page before printing it ...
what i did is i used i frame in the first page and called the page i needed to print
but it fired the query in the first page which should have been fire in the second page after the submission or click of the button ...
so i need to fire the php function after the button click which calls a function in javascript how should i do this?
could anybody help me...
Okay, I am not familiar with your level of PHP knowledge, so I will start with some basics:
PHP is a server-side scripting language. It compiles in real-time when a page is requested. The server processes the HTML and PHP and serves an HTML only page to the browser. You cannot execute PHP code on the client side. There is no way to get PHP code running at the time of a button press without the use of AJAX. You could use AJAZ to make a request to the server at the press of the button and fill the iFrame with the output.
Hope that helps.
so i need to fire the php function after the button click which calls a
function in javascript how should i do
this?
I am not quite clear on why you would need to do this but here it goes...
In the button click handler you want to make an AJAX call. I use jQuery but you can use whatever framework or XMLHttpRequest function you wish.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
function ButtonClickHanlder( e ) {
// Prevent the button from doing something it's normal functions(ie submit form if it is a submit)
e.preventDefault();
// Make AJAX Call
$.post("test.php", { call: "callMe" },
function(data){
alert("Data Loaded: " + data);
}
);
}
$(function(){
$('#clicker').click(ButtonClickHanlder);
});
</script>
</head>
<body>
<a id="clicker" href="#">test</a>
</body>
</html>
Reference: http://docs.jquery.com/Ajax
The test.php page
<?php
if(isset($_POST['call']) && $_POST['call'] == 'callMe') {
callMe();
}
function callMe() {
echo "I am a php function. You rang?";
}
?>