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";
}
Related
When I press on any of the ‘region’ names in the list ('href' links), the matching list of 'cities' is showing underneath.
<?php while(has_list_regions()) { ?>
<?php } ?>
<script type="text/javascript">
function show_region(chosen_region_id)
{
;
$(this).slideDown(200);
;
<?PHP $clicked_tag = 'chosen_region_id'; ?>
}
</script>
Is it possible to include PHP code within a section of JavaScript? Because I need to get the ID of the selected ‘href’ that I clicked. I am trying to include the PHP code in the above JavaScript function but it doesn’t work.
PHP runs on the server, generates the content/HTML and serves it to the client possibly along with JavaScript, Stylesheets etc. There is no concept of running some JS and then some PHP and so on.
You can however use PHP to generate the required JS along with your content.
The way you've written it won't work.
For sending the value of clicked_tag to your server, you can do something like (using jQuery for demoing the logic)
function show_region(chosen_region_id) {
...
$.post('yourserver.com/getclickedtag.php',
{clicked_tag: chosen_region_id},
function(data) { ... });
...
}
In your script the variable chosen_region_id is already in the function so you don't really need to declare it again with PHP.
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?
I am wondering whether this is possible:
I have a page. The user clicks a link and that calls a PHP script. The PHP script returns true or false.
Depending on the true or false, I was hoping to be able to toggle a div.
I am wondering whether I need to do it the AJAX way? How do people usually accomplish this?
Seems pretty common.
I am using this YUI library already:
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?2.8.2r1/build/reset-fonts-grids/reset-fonts-grids.css&2.8.2r1/build/base/base-min.css">
jQuery:
$.post('/path/to/url', {data: 'some data'}, function(data) {
if (data) $('#some-div').show();
else $('#some-div').hide();
}, 'json');
PHP:
echo json_encode(true);
For more information see:
http://api.jquery.com/category/ajax/
http://php.net/manual/en/function.json-encode.php
Yes, you should use AJAX to create a good flow in your site. Instead of implementing your own AJAX handling functions, you could use one of the big JavaScript frameworks, I recommend http://jquery.com/. There, you can read about (and see examples of) jQuery.ajax - http://api.jquery.com/category/ajax/.
This should get you started, but the main idea is to bind that link to an AJAX function, that will call your PHP script, and based on the contents of the returned data, toggle your DIVs on/off.
Good luck!
Set the php script to add a hidden field ... such as...
<input type="hidden" id="passed-value" value="passed-val-is-true" />
Then in your Javascript when you fire the toggle event .. check that element ...
In jQuery would be something like this ...
$foo.click(( if (passed-value.value === "passed-val-is-true") { foo.toggle(); }
Sorry for syntax .. but you should get the general idea.
Also, if you need it to do without page reload, i would def recommend Ajax (pref via jQuery)
Yes, very easy, no need for Ajax. Here's two ways:
Using straight PHP:
<?php
if($test) {
echo "<div>Content...</div>";
}
?>
Or, using inline Javascript (in the PHP script), assuming you have a <div id='targetDiv'> in your HTML, and a $testVar in your PHP:
<script type='text/javascript'>
function toggle(testVar) {
if(testVar) { document.getElementById('targetDiv').style.display = ""; }
else { document.getElementById('targetDiv').style.display = "none"; }
}
window.onload = function() { toggle(<?php echo $testVar; ?>); }
</script>
The second method can be easily altered to degrade gracefully.
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.
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.