Auto refresh using xajax (and MooTools?) - php

For the purpose of testing (and making this question simpler) I have been using xajax to output a random number into a DIV on the page.
$output=rand(20,40);
$ajax_resp->assign('container','innerHTML', $output);
After the DIV container is loaded, I also load 1 line of Javascript to call the xajax function.
<div id="container"></div>
<script type="text/javascript">
xajax_refresh().periodical(2000);
</script>
As you can see, I'm using the MooTools function called periodical() to call the function again after x milleseconds. It calls the function fine at first, but not again.
It doesn't automatically refresh. Why?

You are not assigning a periodical to xajax_refresh function, you are calling that function (with xajax_refresh()). For instance, you're assigning its returned value to periodical (It can be everything, but nothing happens because that returned value is not a function :) ).
Therefore, the solution is this:
<script type="text/javascript">
xajax_refresh.periodical(2000);
</script>

Related

Calling javascript function when page loaded without onclick

I have an footer.php file that have javascript code and functions. I use this footer.php file for all of my pages. When clicking buttons I use
onclick="MyFunc()"
but in some pages I need to call MyFunc without onclick, just when page loaded. I can not use "body onload" function because the tag is in header.php file that all pages is using it. I have triend to put
<script Language="JavaScript">
window.onload=MyFunc;
</script>
in my php file and
<script Language="JavaScript">
function MyFunc(){
alert('hello');
}
</script>
in the footer.php but with no luck.
"but in some pages I need to call MyFunc without onclick"
What I understand from your question is:
You want to fire MyFunc on a few pages
All pages include footer.php (at the end, I assume).
MyFunc is already present
If that's right, you'll have to trigger this event somehow only on the pages that you want it to fire. This can be done two ways.
Add a small snippet to the automatically firing pages
window.addEventListener('load', MyFunc, false);
This code will add the MyFunc function to the array that will be fired when the page is laded. Remember: window.onload and this will fire after all images have been loaded.
Trigger MyFunc automatically
I don't know what the difference between those pages is, but this could be done by firing the function when the page is loaded, just like the snippet I showed above, and just before this is done you check for a trigger. For example, if your page where it fires has an element with a specific class test, simply check if it exists (document.getElementsByClassName('test').length > 0) and then fire MyFunc.
I hope this helps.
if its in the footer (end of the page) you can simply enter this code where you need
<script>
MyFunc()
</script>
this will call the function
as I know the language attribute is obsolete
try to use <script type="text/javascript"> instead of <script Language="JavaScript">
EDIT: put a sample to here jsFiddle
As stated you could use window.onload or you could attach the event to DOM load
<body onload="MyFunc()"></body>

Javascript variable not working in a different file

I have this script in index.php file:
<script type="text/javascript">
$(document).ready(function(){
$('#ads').load('output.php').fadeIn('slow');
});
</script>
And the output.php file contains a hidden input by which I pass a php variable and retrieve it succesfully:
<script type="text/javascript">
num = document.getElementById('number').value;
</script>
And if I put, say, an alert(num); in the output.php file, everything works. Though when I do the same in the index.php file, javascript doesn't seem to see that num variable.
Im just going to ges that you dont actually wait until the file is actually loaded before testing to access that variable
http://api.jquery.com/load/
the load method takes a completed callback that u can use like this
$(document).ready(function(){
$('#ads').load('output.php', function() {
alert(num);
}).fadeIn('slow');
});
but you should probably not solve your problem this way i sugest you call a function from your
loaded file instead of setting a variable
You can't access variables before you create them. In the code you provided the first time num is being assigned to is when the output.php file is loaded and parsed. Since jQuery's load function isn't blocking - that is, your browser will continue executing JS while the load function is doing its magic - you have no good way to know when num will be assigned to. It could be milliseconds, or it could be never if your webserver refuses to return the output of output.php for whatever reason.
In jQuery programming, using a callback function is common practice, although you can make it cleaner by passing it a function reference instead of an inline function:
$(document).ready(function(){
$('#ads').load('output.php', outputLoadCallback).fadeIn('slow');
});
function outputLoadCallback(response, status) {
console.log(num);
}
Maybe an even better way would be to include the logic you need to run in the callback function like so:
var num; // Make sure num is in the global scope
function outputLoadCallback(response, status) {
num = document.getElementById('number').value;
console.log(num);
}
If you're "not much of a pro", may I suggest jQuery in Action?

ReferenceError when Javascript function is inserted via innerHTML

I have a problem calling a Javascript function that was inserted into a <div> via the innerHTML property. I have searched through similar threads in SO, but I wasn't able to find a solution to this problem.
In a simplified version, here is what I have:
MainPage.php
// ... Basic Headers
<div id = 'list'>
{include file="list.tpl"}
</div>
// More stuff...
<script type="text/javascript">
function callbackFunction(data) {
$('list').innerHTML = data.updatedListHTML;
updateCalculatedFields();
}
// Perform a Ajax POST Request with the callbackFunction()
</script>
List.tpl
{if $thereIsData}
// Create a table, populate its content...
<script type="text/javascript">
function updateCalculatedFields() {
// Change some of the values in the created table...
}
</script>
{/if}
With the code above, I get a ReferenceError in the callbackFunction(data) while trying to call the updateCalculatedFields() function. I have double-checked to see that the innerHTML has been properly updated;, the updateCalculatedFields() function (and the whole script tag) has been added to the div. However, Javascript cannot seem to find injected function.
With a small change, the functionality works. If the list.tpl were to be changed to:
List.tpl (version 2)
{if $thereIsData}
// Create a table, populate its content...
{/if}
<script type="text/javascript">
function updateCalculatedFields() {
// Change some of the values in the created table...
}
</script>
The different between the two scenarios is that in the second one, the updateCalculatedFields() function is loaded with the page right from the start. In the first one, it gets added later with the innerHTML. So, my conclusion is that Javascript will not register functions that get added via innerHTML. I highly doubt that this is the case though; so it would be great if someone could give an explanation on this issue.
JavaScript is not evaluated when inserted with innerHTML. You either need to eval() it yourself or append a new external script tag to the page.

AJAX blocking Javascript

Consider the following code:
<script src="js/backgroundChanger.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('.Themes').click(function(){
$('#dcontent').load('printThumbs.php');
});
});
</script>
The first script is for background changing logic and the second script gives list of thumbnails of the themes. The problem is that the first script doesn't work beacause of the second. If I don't use this AJAX technique everything works fine. Working code:
<script src="js/backgroundChanger.js" type="text/javascript"></script>
<div id="dcontent">
<?php include('printThumbs.php'); printThemesThumbs();?>
</div>
The background changing logic looks like:
$(function() {
$('.themes li a img').click(function() {//code
});
Any help will be greatly appreciated.
in your first snippet of the code you defined a click function on .Theme and in the third snippet of the code .theme, is this correct?, i mean both classes seems to be different try to use the same class name return by your php function.
You're calling $(document).ready() twice, as $() is an alias, and the second definition is overwriting the first. First you are setting the document ready callback to
function() {
$('.themes li a img').click(function() {//code
}
and then overwriting it with
function() {
$('.Themes').click(function(){
$('#dcontent').load('printThumbs.php');
});
}
you have to add your second code in a callback function. you can't bind something if it is not already in the dom. if you want to make changes to the printThumbs output you need to add a callback...
<script>
$(document).ready(function() {//this is also a callback function when document is ready
$('.Themes').click(function(){//this can be understand as a call back too... code is fired after a click
$('#dcontent').load('printThumbs.php',function(){/*your callback code here...this code will be fired after you've loaded printThumbs*/}
});
});
</script>
if you want to do some jquery or other client side stuff on the respons of an ajax call (html,xml, json or whatever) you have to specify a callback function. to make things less complicated you have to look at the callback function just as the on document ready function with the difference that the callback is applied to the respons of your ajax call. if the code is not in a callback function you can't manipulate the respons because it is not injected in the dom/it simply does not exists in your browser when the document is ready.

issue calling JavaScript function from PHP

basically I am trying to call a javascript function from my PHP and I am using code I know works in other situations however here is it not and I am at a loss as to why?
It may be something stupid as I have been staring at this screen for a long time :)
here is where I call the function:
if(isset($test_details['done_test'])){
echo "getting here";
echo "<SCRIPT LANGUAGE='javascript'>user_error();</SCRIPT>";
}
I successfully get 'getting here' printed however it does not call the JS function.
javascript function:
function user_error(){
document.write("working");
//alert("User has already taken this test. Your are being redirected...");
//setTimeout("window.location='home_student.php'",3000);
}
The commented it what I do eventually want it to do.
Could anyone please shed some light.
Many thanks,
#Crimson - Here is what I tried after your advice...still no luck.
javascript now:
$(document).ready(function () {
var done = "<?= $test_details['done_test'] ?>";
if(typeof done != 'undefined'){
$('WORKING').appendTo('#bodyArea'); // just to test
}
});
By echoing <script>...</script> with PHP, you are not going to get the browser run the JS function!
PHP only outputs the HTML file that you want to send to the browser. The browser then parses this HTML and does a multitude of things before the page is displayed to the user.
Next, the user interacts with the displayed page (or some other browser related event like 'onload' happens) and the attached JS gets called.
So, if there is some JS that you want to run at a certain time, say immediately after the browser has finished loading the page, you need to create JS in the HTML file such that there is a JS function which gets called at the page load event like this:
<body onload="/*do something here*/"> ... </body>
It is better to use JQuery or some other JS frmework to accomplish something like this though.
Are you sure the function is already defined? Perhaps you declared your function after making the function call.
Additionally, although it's not really going to matter here, the proper way to have a javascript script tag is.
<script type="text/javascript"></script>
i.e. not language="javascript"
Replace the line you call the JS function with this:
echo '<script type="text/javascript">window.onload = user_error </script>' ;
It should solve the problem. Because at the time you are calling user_error(), the function may not have been initialized by the browser. So you'll get an error since the function could not be found.
If the function is placed in an external .js file, it's very likely that you get this error, since the external file usually takes a while to be loaded. If the function deceleration is in the same file but after where you are calling it, same thing happens.

Categories