I have been looking at answers to this across the web for about an hour now, and trying things based on those answers (I know this kind of issue comes up often). However, nothing I am trying is working. So an explanation first:
I am looping through a table in PHP (in a while loop), and need to call a JavaScript function for each record in the row set returned for my table. To try to get started, I have a super basic function that just lets me know I called it ... it's not working. Here's the PHP code (the reason for the DIV tag is that I eventually want to replace the innerHTML of the DIV from the JS code I know how to do that and have done so elsewhere ...):
// the loop:
while( $row = mysqli_fetch_array( $heralds_result ) )
{
$herald_id = $row["roster_id"];
$sca_name = $row["sca_name"];
// create a div for each herald as we go with its' own name (using id ...)
echo " <div id='" . $herald_id . "'>\n";
echo " " . $sca_name . "\n";
echo " <script type='text/javascript'>test();</script>\n";
echo " </div>\n";
}
This is the JavaScript code (at the bottom of the file):
<script type="text/javascript">
function test()
{
alert( "Test function" );
}
</script>
However, I get no "alert" dialog, just the text streamed out. So for the first row I get:
<div id='1'>
Aasa Thorvaldsdoittr
<script type='text/javascript'>test();</script>
</div>
As the alert dialog is not displayed, it tells me the Javascript function is not being called, or there is some error that is truly not obvious to me after staring at it for a long time. This is something that shouldn't be this difficult, I am sure I have some really obvious error that someone will see as soon as they look at the code, but it's evading me completely.
"JavaScript code at the bottom of the file"
is the problem. Scripts are run as soon as they are added to the DOM. Things are added to the DOM in the order they are given in the HTML.
Therefore the script tags which try to call your function are added - and executed - before the script tag which actually contains the function gets added. So they try to execute a function which doesn't yet exist. If you look in your browser's Console (in the Developer Tools) you probably have some errors complaining about this.
The simple solution is to declare the script tag containing the function somewhere in your HTML before the code which tries to use it.
As an aside, it would be interesting to know what you plan to do with this function in reality - consider whether you could achieve the same effect directly by creating some markup using PHP, rather than firing off lots of JS while the page is loading.
You should move the function declaration upper than it used. For example:
<script type="text/javascript">
function test()
{
alert( "Test function" );
}
</script>
..
<?php
..
// your loop
..
?>
or
<?php
..
echo '<script type="text/javascript">
function test()
{
alert( "Test function" );
}
</script>';
..
// your loop
..
?>
Related
I am stuck with this issue. I have a js function into a scripts.js file:
var userLoggedIn;
function openPage(url) {
if(url.indexOf("?") == -1) {
url = url + "?";
}
var encodedUrl = encodeURI(url + "&userLoggedIn=" + userLoggedIn);
$('#mainContent').load(encodedUrl);
}
I call the javascript function from a php file like this:
<?php
//This file should check if the requested url is sended by AJAX or it's manaually typed by the user into the browser
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
include 'includes/config.php';
include 'classes/Artist.php';
include 'classes/Album.php';
include 'classes/Song.php';
} else {
include 'includes/header.php';
include 'includes/footer.php';
$url = $_SERVER['REQUEST_URI'];
echo "<script>openPage('$url')</script>";
exit();
}
?>
It works fine when it's called from an onclick event into the HTML document, but it doesn't works when I enter manually the url. It prints a string into the screen. However this code is taken from some sample coding pages and it seems to work this way. What am I missing here?
Thanks in advance for the help and be patient... i'm a beginner on this!!
First of all you need to have the mentioned above js code loaded somewhere. Do you have it loaded in header or footer? (Directly or by loading your scripts.js?)
Be sure to have:
<script type="text/javascript" src="scripts.js">
Somewhere printed in your code. Do you have it in your footer or header?
Assuming that you have your js code in scripts.js now you can execute after page loads, but be sure print the <script> part WITHIN your <html>...</html>. So if you print out </html> in your footer.php then be sure to print:
echo "<script type="text/javascript">openPage('$url')</script>";
BEFORE loading of footer (but after loading of scripts.js);
While you learn a bit more you will get to know that actually it is a bad thing to execute code parts like that: you should separate your markup from code which executes things directly from it.
Modern frameworks will assist you with that, there is also defer attribute of the script element (https://www.w3schools.com/tags/att_script_defer.asp) which helps to execute the code after the page actually loads.
So, after reviewing all the code i found the problem. There was a missing ">" in the html closing tab. Now it works!! Thank you for your help!
So I am trying to get this code to echo my popup when class elements are clicked. I have the code in the head section of my wordpress file but it's not working. Any ideas?
I've even tried moving the variable around and still nothing
<?php
function popCash() {
$doit = "<script type='text/javascript'>
var wid = '111111';
var uid = '111111';
</script>
<script type='text/javascript' src='//cdn.popcash.net/pop.js'></script>";
echo $doit;
}
?>
<script type='text/javascript'>
$(document).ready(function(){
$('.post-thumbnail, .thumb-block, .display-img').click(function(){
var <?php echo popCash;?>
});
});
</script>
I need it to show the popup when the class elements are clicked
Depending on what kind of result you want, you need to use console.log(popCash) or alert(popCash), not echo, which is not valid JavaScript.
Follow-up after comment:
If you're trying to execute that script, it's more like document.write(popCash) that you'd be looking for, but this wouldn't be a very efficient way to accomplish what you're trying to do because you'd be loading up that script every single time you got a click, and accumulating additional <script> elements with every click.
For one thing, it looks like you're assigning values to global variables wid and uid using a script. There's absolutely no good reason to create a new script just to do that. Simply assign the variable directly:
<script type='text/javascript'>
var wid;
var uid;
$(document).ready(function(){
$('.post-thumbnail, .thumb-block, .display-img').click(function(){
wid = '111111';
uid = '111111';
var popCash = "<script type='text/javascript' src='//cdn.popcash.net/pop.js'>\n"+
"<\/script>";
document.write(popCash);
});
});
</script>
But then the question becomes: "Why reload the 'cdn.popcash.net' for every click?"
Isn't there a method inside the script that can be called whenever it needs to be invoked again?
And even if the script is so poorly written that it must be run from the top for every invocation (that's a terrible API!), you can at least dynamically create and delete script tags to do the job instead of using document.write(), but that would take a bit more explaining to describe.
I have a webpage that uses PHP that must be output before any code is called. In another part of my PHP I need to call a JavaScript function for displaying a message on certain user actions. Is there a way I can call my JavaScript function at the top of my page? I'd rather keep all the PHP together as currently it looks like this;
<?php
...Code that must be called first...
?>
...<head></head>....
<?php
if (PHPFunction()){
echo "<script>MyJSFunction();</script>";
}
?>
To me it looks messy having it this way. How can I avoid this?
EDIT:
To make my intentions more clear. The JavaScript function I'm using will display a pop up message, giving the user feedback on actions they are performing. For example, if they upload a file, if move_uploaded_file() is successful, this message gets called. The browser complained when I had my bottom code in the top part saying that my JavaScript function was not defined. When I moved it under it was all good, apart from now looking messy.
Are you using jQuery ?
if you are, have you try this code:
<?
move_uploaded_file(source, destination);
echo "<script>
$(document).ready(function () {
alert ('file successfullu uploaded');
});
</script>";
?>
The purpose of this code was to populate a div from a PHP file when a button is clicked.
Also to pre populate a div when page loads - I have completed this task.
Now I want to load a second div at the same time and I'm unsure how to go about this.
function loadpage(clicked_id) {
if (clicked_id != 0 || clicked_id != null || clicked_id !="") {
$("#Table").load("marshfight1.php?action=fight&id="+ clicked_id);
$("#mobs").load("marshtab.php");
}
}
$(document).ready(function() {
// initial
$('#mobs').load('marshtab.php');
});
Echo "<div id=Table></div>";
Echo "<div id=mobs></div>";
$selem = mysql_query("SELECT * FROM senemies WHERE userid='$playerinfo[id]' && arena='10'");
while($enem = mysql_fetch_array($selem)) {
Echo "<button><type=button id=\"$enem[id]\" onclick=\"loadpage(this.id)\" name=\"$enem[id]\">$enem[name]<br>Level: $enem[level]<br> HP: $enem[hp]</a></button>";
}
Everything works fine except for the second .load to update #mobs.
The problem appears to be the inclusion of PHP in your javascript. Remember that though PHP will throw a compile error, IE will do its best and FF will do its best up to the point of the error then very quietly quit. Thus it will appear to be working but actually half your code never gets executed. ctrl-shift-k in FF will give you a rundown of errors.
What you need is ajax. This is easy to implement in both jquery and 'straight' javascript.
Forgive me if you already know this, but others use this forum so a brief summary of the process would be:
Button is clicked triggering JS onclick function.
onclick function sends appropriate data (which button for instance and/or usernumber etc) to php file.
onclick function puts whatever the php returns in the div as desired.
You need to get your js and php organised and separated.
A good overview and basic tutorial can be found at http://www.w3schools.com/ajax/
I have looked at other questions similar to this, but I haven't found an answer.
My <body onload="doStuff()"> has stopped calling the doStuff() JavaScript function. I have tried replacing <body onload="doStuff()"> with <body onload="alert('Test');"> and that creates the alert successfully.
Then I tried putting that same alert just inside the doStuff() function (and reverting the onload to call doStuff()), but the alert did not appear.
Are there any reasons why this would happen? Also, it may be relevant to note that I am almost certain that I did not make any code changes in between this working and it not working (you may not believe that, but it's true); however, I did delete a sub-folder from the server that contained a Joomla installation.
Make sure that your script tag is correct.
<script src="myscript.js" /> will cause <body onload="...">...</body> to fail.
It should be:
<script src="myscript.js" type="text/javascript"></script>
Try to move away from inline calls and utilise jQuery as it was intended. Its really good working practice, (not to mention easier to debug) by keeping your style, and script logic separate.
for body on load, use this.
$(document).ready(function () {
doStuff();
});
or it can be shortened even further to
$(function () {
doStuff();
});
For whatever reason in firefox, my Scripts declared in the body of the page was preventing inline calls from firing. I moved my script tags to the header and then it worked.
The issue with the uncaught syntax error (see comments in original post) was that, when I was converting a PHP array into a JavaScript array, something was going wrong, i.e., a weird character was being appended. I solved this by replacing my DIY PHP-array-to-JS-array code with this code:
<?php
$js_array = json_encode($resultsArray);
echo "var jsResultsArray = ". $js_array . ";\n";
?>
This isn't really connected to the headline question of the post, but it was the root problem.