php script calling parent javascript function - php

I have this folder structure:
index.php
js/scripts.js
In index.php I have a JavaScript function defined called execute().
Now within index.php I have a form that when submitted will call email.php and at the end of the execution of the email.php I do this:
echo '<script type="text/javascript">parent.execute();</script>';
This all works fine.
Now when I move execute() into scripts.js and I put this line of code in index.php:
<script type="text/javascript" src="js/script.js"></script>
then email.php is somehow unable to find execute() function. I know this because if I modify the execute function only the original version (the one that was in index.php) is ran.
I know this is weird, but I am new to this and I don't know of anyway I can debug this. Is there something obvious that I am missing?

First, make sure you don't have a typo in your <script> tag. You've referred to your external script file as both script.js and scripts.js. One little 's' can make all the difference.
Assuming you've included your script correctly, most likely, you have put execute within another function, thus taking it out of the global scope. That would be the case if script.js looks something like this:
(function () {
...
function execute () {
...
}
})();
If that's the case, move execute out of it's containing function. You can also put execute in the global scope by explicitly making it a property of window:
window.execute = function execute () {
...
};
If you do it this way, it's fine to leave execute within another function.

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?

jquery not working when i'm not putting it inside a jQuery(document).ready

jQuery(document).ready(function(){
jQuery(".test").click(function() {
alert(1);
});
});
When I try not to put :
jQuery(".test").click(function() {
alert(1);
});
inside a jQuery(document).ready() it won't work.
What do you think is the cause of that one? I already loaded the custom script that has that function.
<script type="text/javascript" src="/scripts/js/jquery.js"></script>
<script type="text/javascript" src="/scripts/js/customScript.js"></script>
Any answer would be appreciated and rewarded.
Thanks!
If you're loading it in <head>, then your .test hasn't loaded yet at the time when your code executes. Thus, jQuery(".test") returns [], so the click event gets attached to nothing. If you move your <script> to the last thing in <body>, it should work.
The behaviour you are seeing is normal and correct.
When you say:
jQuery(".test").click(function() {
alert(1);
});
It means "find all elements that exist right now with the class 'test' and assign a click handler to those elements". If you put such code outside the document ready then the browser will not have parsed any HTML that is after that bit of script so it will not find any elements defined further down the page - they don't exist in the DOM yet.
Putting the code inside document.ready (or in an onload event handler) means that it won't be run until the whole page has been parsed, at which point all elements will exist and can be accessed from your code. (It should also work if you put it right at the bottom of the page after all the HTML.)

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.

Problem calling a js function from php

I am using my php to call a js function like this:
<?php
$chk=1;
if($chk==1)
{
echo '<script>testing();</script>';
}
?>
and my js looks like:
function testing()
{
document.getElementById("mainbody").innerHTML="This is my first JavaScript!";
}
The js is an external js file.
My html looks like:
<html>
<head>
<script src="qotw.js"></script>
</head>
<body>
<div id="mainbody"></div>
</body>
</html>
but this is not working. What am i doing wrong over here?
Please tell me if you know.
Best
Zeeshan
You run the script before the div you are targeting exists, so the document.getElementById call returns a false value instead of an HTMLElementNode.
You either need to move the script element so it is after the div, or assign the function to an event handler (onload for instance) instead of calling it directly.
This has nothing to do with the use of PHP.
Incidentally, your HTML is invalid and triggers quirks mode.
Try testing the following in order:
first: Your script is being called
<script type="text/javascript">alert("hello");testing();</script>
second: The function is being called
function testing() {
alert('inside testing');
}
third: As suggested above,
if (document.getElementById("mainbody") == null) alert('yep, its null');
then let us know the results
Make sure that 'testing' isn't called above 'mainbody' in the code, because then the code would be run at a point during load, when the object doesn't exist.

Categories