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.
Related
I am building a simple website using php in a mvc fomat and I'm trying to use ajax to call a simple clock but having trouble. Right now im just tyring to get a "hello world" example in my code to get started and go from there. An example format of my php class is : (the hello.php just echos hello world, and a Run() is being called at an index.php). For the life of me I can not get the script to work , any help would be appreciated.
Thank you.
<?php
class MyFile{
public static function Run(){
MyFile::show();
}
public static function show(){
echo 'html stuff';
?>
//run this sample ajax script i found //
<body>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$.get("hello.php", function(data){
alert(data);
});
});
</script>
</body>
<?php
}
}
?>
If we disregard the fact that your provided example code is a mess of PHP + HTML.
The provided code works just fine if you know how to call it via php, e.g.:
$obj = new MyFile(); // instantiate obj/class
$obj::Run(); // execute static method
Advice in general: try to avoid writing mixed "view (html)" + "logic (php)" code especially like the example you provided where it's a class no less.
If you can't help it at least you can make it look cleaner by using include or similar in php.
Here is a bit of longer explanation why you should try to avoid mixing:
Should I Include PHP code in HTML or HTML in 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.
I have the following in the body of a php page:
<?php if($foo) : ?>
<script>
js_func();
</script>
<?php else: ?>
//Do Something else
<?php endif; ?>
Based on the PHP conditional I either do or do not want to run js_func().
However if I am loading all of my scripts (including the script the defines js_func()) at the bottom of my page this will results in an error.
One possible solution would be to load the external script BEFORE calling js_func() but I understand that for performance reasons I shouldn't do that.
I could use $(document).ready(function() {}); but this just moves the error as jQuery is also loaded in the footer.
The only other options I can think of is to use window.onload or never call a js function inline. How does everyone else solve this issue?
Many thanks.
EDIT:
#Nile - Im not sure what you mean. Why would I comment out code that I want to execute?
#haynar1658 - I don't want to execute JS in the else scenario.
#Matthew Blancarte - Understood. That leads to my question, what's the best way to make sure that the js I need loads before that function is instantiated? Include the script before it? Use window.onload? etc.
I think you are making a rod for your own back. Depend on the question you described, you want to put all the function definition script block after the place where them being called. It's Impossible!
If you indeed need to do this, does this can help? :
<script>
var fns = []; /* use fns to keep all the js code
which call the functions defined after. */
</script>
<script>
//wrapp your code in a function and then push it into fns.
fns.push(function(){
js_func();
})
</script>
//script tags for loading your function definition js script.
<script src="path/to/jquery-any-version.js"></script>
<script src="path/to/other-libraries.js"></script>
<script>
//after your definition js scripts are loaded , call all functions in fns
for(var i=0, len=fns.length; i<len; i++){
var fn = fns[i];
fn.apply(this, []/* arguments that provided as an array */);
}
</script>
Just move the script to the top.
The difference (if there is one) is very small.
The believe that putting the <script>s in the <head> slows down the page is not "accepted" by all developers.
Did you try to echo it in PHP?
<?php if($foo) {
echo "<script> js_func(); </script>";
}else{
echo "something else";
}
I have php file called "PhpCallJavascript".
I try to call to function CreateSVG() from php code.
it is not working should I need here ajax?
or somthing else?
thx for any help.
the php file:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<?php echo '<script type="text/javascript">', 'CreateSVG();', '</script>'; ?>
<script>
$(document).ready(function() {
function CreateSVG(){
var xmlns = "http://www.w3.org/2000/svg";
alert(xmlns);
}
});
</script>
You have two main problems.
First: Functions are not hoisted between script elements
If you call a function inline (without waiting for a suitable event), then the function you call must either be declared in the same script element or an earlier one.
Second: Functions declared inside other functions are scoped to that function
Since you have declared CreateSVG inside an anonymous function (which you then pass to ready()), you cannot access CreateSVG from outside that anonymous function.
A fixed version of the code would be:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function CreateSVG(){
var xmlns = "http://www.w3.org/2000/svg";
alert(xmlns);
}
CreateSVG();
</script>
<?php echo '<script type="text/javascript">CreateSVG();</script>'; ?>
Try this?
EDIT-
Apologies, read the way it was written wrong. Was assuming he had a syntax error when the function itself just needed to be moved.
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.