I have a php code, which is in a div. It shows a random text placed in the random.txt file. I want to refresh this div, to load new text in every - let's say - 15 seconds without refreshing the whoe page.
I've found several solutions to reload divs without refreshing a page and it seems it can be done with AJAX or JS, but they only refresh it with a specific content or a specific file, however I can't figure out how to insert this code and have it refreshed.
This is how my div looks like:
<div id="randomtext">
<?php
include_once("GetRandomText.php");
$MPTextFile = "random.txt";
$MPSepString = "*divider*";
$MPTextToHTML = false;
MPPrintRandomText($MPTextFile, $MPSepString, $MPTextToHTML);
?>
</div>
It loads a random text to the div at every refresh.
I tried to refresh the div it with the JS below, but it's not working at all. Sorry, I'm not good in it.
<script>
var auto_refresh = setInterval(
function () {
var newcontent= '<?php
include_once("GetRandomText.php");
$MPTextFile = "random.txt";
$MPSepString = "*divider*";
$MPTextToHTML = false;
MPPrintRandomText($MPTextFile, $MPSepString, $MPTextToHTML);
?>';
$('#randomtext').html(newcontent);
}, 1000);
</script>
<div id="randomtext"></div>
Thanks in advance.
PHP Script and Javascript are executed in separate environments. (Your server and user's browser, respectively.)
What you need to do is to move the embedded PHP script into a separate PHP file. And using somthing like this:
content.php
<?php
include_once("GetRandomText.php");
$MPTextFile = "random.txt";
$MPSepString = "*divider*";
$MPTextToHTML = false;
MPPrintRandomText($MPTextFile, $MPSepString, $MPTextToHTML);
?>
Inside your html page
<script>
var auto_refresh = setInterval(
(function () {
$("#randomtext").load("path/to/content.php"); //Load the content into the div
}), 1000);
</script>
<div id="randomtext"></div>
Document for jQuery Load function: http://api.jquery.com/load/
As far as I understand you, you are trying to execute your PHP in a browser which is not possible. Your server parses the PHP and replaces that code with the random string.
You need a AJAX request to your server which evaluates this script and sends it back to the client. In a simplified way:
request = new XMLHttpRequest();
request.open("GET", "my.php");
request.send();
$("#randomtext").html(request.response);
Related
I have one input and script to reload table in my page. In the input if I insert 1000 I want to reload page every second, without clicking any buttons.
This is what I tried :
<input id="txtRefresh" />
<script>
document.redy(function () {
$('tblRefresh').load();
setInterval(function () {
$('#tblRefresh').load();
}, 'txtRefresh');
});
</script>
Its cshtml razor page.
What I want to do is to insert the value of seconds in the input andrefresh the page based of the of the inserted value, without submiting any data.
Is it possible to do this? Any suggestions?
Thanks in advance!
UPDATE
I inserted this script:
<script>
document.ready(function () {
$('#refreshDIV').load('url/url/url');
setInterval(function () {
$('#refreshDIV').load('url/url/url');
}, $('#txtRefresh').val());
});
</script>
But it gaves me error!
refreshDIV is a div that I want to refresh
txtRefresh is the input from I insert the seconds
you can try this:
$(document).ready(function(){
var timeout = $("#txtRefresh").val();
setTimeout(timeout, function() { location.href=""; });
});
but each time you will reload the page you will lose, the input.
You could send it through querystring like this:
location.href="?timeout="+timeout
and populate the input server side
This is just a string:
'txtRefresh'
If you want to get the value of that element, it would be more like this:
$('#txtRefresh').val()
You also have a typo in document.ready and in your first #tblRefresh selector (missing the #), and you aren't supplying .load() with the URL you want to load. All together you appear to be trying to do this:
$(document).ready(function () {
$('#tblRefresh').load('/some/url');
setInterval(function () {
$('#tblRefresh').load('/some/url');
}, $('#txtRefresh').val());
});
A couple things to note:
The value /some/url is of course a placeholder in this sample code. Whatever URL you want to use in your application is up to you.
Calling .load() will place the entire response of that URL into the target element. If you want only a subset of that response, you can add selectors to .load(). For example:
$('#tblRefresh').load('/some/url #someElement');
This would tell .load() to grab all the content from /some/url and then only select from it the content of #someElement to place in #tblRefresh. The performance could still potentially be slow as all of the content from the URL is still downloaded. To address performance or for finer control over data, consider returning JSON data from the server and using .ajax() to fetch that data instead of using .load() to reload all of the HTML (when only the data has changed).
index.php
<script>
var example = 1;
$("#example-div").load("external.php");
</script>
<div id="example-div"></div>
external.php
<script>$("example-div").innerHTML("BlaBla " + example);</script>
Hi,
I am currently loading content from another file into my index.php with the load() function of JQuery to load images only then when I want it for example.
Now I am using a database connection which i define in my index.php. When I load the external content now, the code I load doesn't now all the variables I defined previously in the index.php, although it's part of index.php after loading them.
Is there a way to let the loaded content now all the previous stuff?
Thanks y'all!
You want to use session cookie to save data in php and for javascript you want to use cookie then use cookie and session any page
for php
https://www.w3schools.com/php/php_sessions.asp
https://www.w3schools.com/php/php_cookies.asp
for javascript
https://www.w3schools.com/js/js_cookies.asp
Jquery have some callback function executed when the load is finish, you can execute the script in external.php in this callback function, because at the moment your function will be execute, the content is in the DOM and it should work.
var example = 1;
$("#example-div").load("external.php", function() {
$("#example-div").innerHTML("BlaBla " + example);
});
It's a bit strange for me to use a script from the page you loaded to perform some task in the current document.
I don't know what you are trying to do. But your code is working, just small mistakes. Do it as follows -
index.php
<div id="example-div"></div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
var example = 1;
$("#example-div").load("external.php");
</script>
external.php
<script>$("#example-div").html("BlaBla " + example);</script>
This gives the output
BlaBla 1
I have a php page that runs standalone without any issue.
When I open the page it includes a js file with some functions. What I am interested in is that the JS contains a
window.onload = function() {
//my js stuffs here
}
that fires when the php opens.
Next step was to move the php inside my framework loading it in a div of an existing page.
So in the framework I did
$('#destinatario').change(function(){
var hk = $(this).val();
$('#sotto').html('');
$('#sotto').load('../websocket/index.php?hk='+hk);
});
my page keeps loading fine without any inconvenient but the window.onload never gets fired. What am I doing wrong?
Yes, you could workaround this doing:
$('#destinatario').change(function(){
var hk = $(this).val();
$('#sotto').html('');
$('#sotto').load('../websocket/index.php?hk='+hk, function (){
window.onload();
});
});
if it does not work create a function on index.php something like loaded() and then in the callback to when the index.php is loaded call that function.
I have a small script written in JavaScript that is used to change picture every second. The problem is that image is not being changed.
The image file that shuld be displayed is overwritten every second, with the new data.
Displaying the first image on the webpage works fine, but getting all of the subsequent images does not work, always the same picture is displayed.
JQuery code contains time extension to force the browser to reload new image every time and to not take it from the cache.
You can see the JQuery code for image loading.
<script type="text/javascript">
var auto_refresh = setInterval(function (){
$('#image').load('camera_stream_worker.php?time=' + Date.now());}
, 1000);
</script>
This is the return of the worker file:
<?php
echo '<img src="/RAMdisk/image.jpg" />';
?>
On the picture ou can see the network traffic.
So my question is: how can I display different picture every second?
thanks
ajax method:
may need to specify different content-type in the header.
$.ajax({
method: 'get',
url: 'camera_stream_worker.php?time=' + Date.now())
}).success(function(data) {
$('#image').html(data);
})
Could be that the image names are all the same, therefore it doesn't get new ones. try to add a timestamp to your images:
<?php
echo '<img src="/RAMdisk/image.jpg?<TIMESTAMPHERE>" />';
?>
this answer assumes the result were image srcs.
have you tried changing the src instead of load?
<script type="text/javascript">
var auto_refresh = setInterval(function (){
$('#image').attr('src', 'camera_stream_worker.php?time=' + Date.now());}
, 1000);
</script>
The issue here appears to be the fact you are returning an html document instead of just the image that is changing. The HTML has a hardcoded image.jpg in the source and since that does not change it is being pulled from the cache.
What you would need to do is change that image source to fetch the latest image and not update the entire html snipplet around it.
Other option is to make the php append the timestamp to the html.
I am trying to call a JavaScript function after load...like totally after the page loads. It's part of a chatroom I'm designing, in which a cron repeatedly checks for new data, and if there's new data, it tells the chatroom index.php that there's new data. The page then prints some javascript, but the page has already loaded. How do I call the functions and lines of execution after the page has loaded? Thanks so much in advance!
EDIT: Here's the code:
if($connection) {
$sql = "SELECT * FROM `refresh` WHERE `refresh`=1;";
$query = mysqli_query($connection, $sql);
$result = mysqli_fetch_fields($query);
if($result !== null) {
?>
<script type="text/javascript">
refreshChat();
$.ajax({url: "chat.log", type: "POST"})
.done(function (data) {
$("#chattxt").html(data);
});
</script>
<?php
}
}
//More code irrelevant to this problem.
The JavaScript function refreshChat() is simply the same code I put after the call to it. I have also tried heredoc, and it didn't work either.
You want the window.load() event. Here's a jQuery example;
jQuery(window).load(function () {
// page loaded, do stuff
});
You could also call this on a specific tag (<body>, for example) as onload="".
<body onload="...">
jQuery
$(document).ready(function() {
// DOM Loaded
});
JavaScript
document.onload = function() {
// DOM loaded
};
After sitting on the problem and thinking about it, I realized that what I was trying to do won't work. The PHP is translated before the page is loaded on the screen at the server, and then after it loads, nothing else can happen. I need to move this over to the client and to JavaScript. Thanks though, and sorry for posting an impossible question!