Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
25
rated 0 times [  27] [ 2]  / answers: 1 / hits: 23810  / 11 Years ago, thu, january 16, 2014, 12:00:00

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.


More From » php

 Answers
96

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/


[#73115] Thursday, January 16, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyaleenag

Total Points: 678
Total Questions: 121
Total Answers: 105

Location: Papua New Guinea
Member since Thu, Jul 9, 2020
4 Years ago
harleyaleenag questions
Thu, May 5, 22, 00:00, 2 Years ago
Wed, Aug 19, 20, 00:00, 4 Years ago
;