Call JavaScript function after page completely loads - javascript

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!

Related

Script getting executed correctly once page is refreshed - jquery

In my webpage I have script like this :
<head>
<script src="scripts/effect.js"></script>
<script>
if (document.readyState == 'complete') {
doOnLoad();
}
$(window).bind("load", doOnLoad);
function doOnLoad() {
console.log("here..");
}
</script>
</head>
effect.js file contains script as shown below:
$( document ).ready(function(){
console.log("yes");
// here I've script for reading a text file using ajax and manipulating the result from text file
$.ajax({
// code goes here
console.log("ajax");
});
});
The problem is that when I run the page initially, I'm not getting the result. At that time I get console output as
yes
here..
ajax
But when I refresh the page again I am getting the result and console prints like :
yes
ajax
here..
How can I run window.load after the document.ready is completed.
Can anyone help me to fix this? Thanks in advance.
This is all about the timing of script execution. It sounds like the behaviour is changing once certain resources have been loaded and cached.
The first piece of code you have is a bit confusing:
if (document.readyState == 'complete') {
doOnLoad();
}
I'm not sure why you need this as well as the on load handler? It looks like that condition is never going to equal true anyway, as that code will run immediately before the document has finished loading. At the very least, I would put a console.log in this block, so I could determine what's triggering doOnLoad.
Try replacing the script on your page for just the following:
$(window).on("load", doOnLoad);
function doOnLoad() {
console.log("here..");
}

issue with window.onload in included file

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.

How do I dynamically read from a file using PHP as new information is written into it

I have a code set up where I use JS and PHP to write to a file and display the output to a html element (in this case a textarea). I have a huge problem about how to go about this. I know that PHP is executed before anything else happens. I use php to echo the file content using my own javascript function
output(string) // this outputs whatever into the html element text area
PHP:
<?php echo "output('".$someText."');"; ?>
Now my problem comes around when I update and add contents to that file, but the php has already been executed and trying to read from the file again, will only display results from the last time it executed the php. The only way around this is to refresh the page, thus 'rebuilding' the html content of the file.
This whole code of mine mimics the look and feel of a command line ( you have an output screen with an input box) How can i dynamically display the contents of a file as new content is being added to the file without having to refresh the window. Refreshing the window will work, but not at all what i need for this to work. Any help with this?
For more information about how my code is structured, below you will find a snippet of how the code executes:
// main.php
<?php
// displays the file into the output box
function displayFile($fileName){
$file_handler = fopen($fileName, "r");
while (!feof($file_handler)){
$line = fgets($file_handler);
$line = formatFileLine($line);
echo "output('".$line."');";
}
fclose($file_handler);
}
?>
switch(splitCmd[1]){
case 'permitted':
output('\nWells that have been permitted:\n');
<?php displayFile('permitted.txt'); ?> //calls the php function to display content.
break;
case 'drilled':
output('\nWells that have been drilled:\n');
<?php displayFile('drilled.txt'); ?>
break;
default:
output('Wrong syntax: show <permitted, drilled>');
}
You can do this with an AJAX request, there are multiple ways to do this, but the easiest is with jQuery (opinion based ofcourse!), here is a link to the documentation. jQuery AJAX
Example:
function ajaxCall(){
$.ajax({ url: 'PHPFILE.php',
success: function(e){
//e is what you get returned from the php file
$('#div').html(e);
}
});
}
Oh, and you should ofcourse have the jquery library linked. which you do this way:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
You need to make an AJAX call to your PHP file. Take the output from the PHP script, and embed this into, say, a given div on your page.
Let's pretend you have a div set aside for display. Let's give you a button to refresh it whenever.
<div id="resultdiv"></div>
<input type = "button" id="rbutton" value="Click to Refresh">
Style it any way that you please.
Now, let's set up an AJAX call to load the results from the PHP.
<script type="text/javascript">
$(function() { //document ready psuedonym
function refreshdata(){
$.ajax({
type: "POST",
url: "my_data_script.php",
dataType: 'html',
data: {myparam1: 'abc', myparam2: '123'}, //these are optional parameters in case your PHP script needs them
success: function(data){
$('#resultdiv').html(data);
},
error: function(){
},
complete: function(){
}
}); //end ajax
} //end function
$("#rbutton").click(function() { //clicking the button refreshes the data on demand
refreshdata();
});
refreshdata(); //this will run the function when the page loads
});//end document ready pseudonym
</script>

Calling JS function from html/php file without button

I'm trying to call my JS function which is in a file called Scripts.js. I have a php function, but I'm unsure as to whether I need to come out the php function or not as I can't get it to work either way and nothing I've googled is giving a definitive answer as to which it should be so any help would be appreciated!
<?php if(isset($_REQUEST['renameFile']))
{
//uses checkboxes from table
if(isset($_POST['checkbox']))
{
$checkedboxes = $_POST['checkbox'];
$count = count($checkedboxes);
//echo ("$count");
/*if($count == 0)
{
throw error that something needs to be selected. If implement checkbox hidden then no need to implement
}*/
if($count == 1)
{?>
<script type="text/javascript">
showUpload();
</script>
<?php
}
?>
So I'm calling the function showUpload() in my Scripts.js file which I have defined in my main screen using
<script src ="Scripts.js"> </script>
Which I know works as I've used it elsewhere.
function showUpload()
{
document.getElementById('fileUpload').style.display = "block";
}
And then this goes on to call a pop up form which I can get to work on a button click so it's just calling it without a button which seems to be an issue. Thanks!
check following things.
include your js file at the top of the file
write the script tag out side the php mode.
make sure the if conditions are true/false as you expect
then the code should work fine

Refresh a div which contains a PHP code, without refresing the page

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);

Categories