0

This question is not a duplicate of some of the other PHP & Javascript questions that have been asked here before, at least not one I have been able to find.

I have a .php file that contains some HTML elements that get rendered by the PHP for the sake of argument here we will say the file is located at http://url.php. It is looking for certain GET tags, and including a div if those get tags exist.

<?php if(isset($_GET['VAR']))
{
   echo '<div id="VARDIV"></div>';
}?>

Of course I realize that this all happens on the server, and gets sent back to the clients web browser where the javascript takes over.

But in the javascript (on the same PHP page) I have the following code that executes on page load looking for that div tag and doing something with it:

if(document.getElementById("VARDIV")!==null)
{
     alert('div exists!');
}

While the page loads this should logically pop up the div if the URL is http://url.php?VAR correct?

However it does not. If I run the javascript code a second time in the console it works fine, so its not a misspelling (such as getElementsById or something silly like that).

How can this possibly render out of order like this? Should the PHP engine not render the HTML then pass it back to the browser before one line of JS is executed?

EDITED FOR CLARITY BASED ON COMMENTS BELOW:

<script type="text/javascript">
    function doDIVStuff()
    {
       if(document.getElementById("VARDIV")!==null)
       {
        alert('div exists!');
       }
    }
doDIVStuff();
</script>

<html>
   <body>
      <?php if(isset($_GET['VAR']))
      {
      echo '<div id="VARDIV"></div>';
      }?>
   </body>
</html>
dynamphorous
  • 739
  • 1
  • 9
  • 20
  • Are you doing that once the DOM has rendered in the browser? In other words are you waiting for the document to load? Is your javascript at the end of your rendered page? – Jay Blanchard Aug 19 '14 at 17:20
  • Are you asking me if the javascript is physically located at the end of the php text file? – dynamphorous Aug 19 '14 at 17:21
  • He's asking if you're wrapping your DOM-pertinent code inside a document ready handler - https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded. – Mitya Aug 19 '14 at 17:22
  • Yes. I am asking that because I am trying to determine if your browser has rendered the DOM yet. And what @Utkanos said. – Jay Blanchard Aug 19 '14 at 17:22
  • Show us what code you use to "execute [that snippet] on page load" – Bergi Aug 19 '14 at 17:23
  • I will append the question to include the relevant code. But the answer to your question is that the javascript is at the top of the page, and the HTML in question is located closer to the bottom... I take it that is my problem? – dynamphorous Aug 19 '14 at 17:24
  • 3
    Are you sure it's not a duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/q/14028959/1048572)? – Bergi Aug 19 '14 at 17:24
  • If that's all what is in your ` – Bergi Aug 19 '14 at 17:25
  • Yes @dynamphorous, that is the problem. Have a look at the link Bergi supplied. – Jay Blanchard Aug 19 '14 at 17:26
  • What about adding a timer on your script? – racecarjonathan Aug 19 '14 at 17:26
  • Ok, I see in the link that @Utkanos supplied that i needed to use the DOMContentLoaded to do what I was doing. I just thought that the browser would wait for the whole HTML page before executing – dynamphorous Aug 19 '14 at 17:28
  • i don't understand... It works fine on mine – g-newa Aug 19 '14 at 17:28
  • @g-newa What I included above is a VASTLY shortened version of what I'm actually running to show the problem as clearly and cleanly as possible. I did not check the EXACT code, but it was irreverent since it was so over simplified. I just wanted to understand why it was that a rendered page on the server was not rendering first, then getting sent, then having a script on that page run. – dynamphorous Aug 19 '14 at 17:31
  • there you are.. place script at the end of file... please look at my answer below – g-newa Aug 19 '14 at 17:36

6 Answers6

2

use either window.onload() or document.onload(), see differences here

you could also place your script just before the end of your tag in the html although there could be unintended consequences in certain things in IE, seen here

Community
  • 1
  • 1
Jack
  • 172
  • 13
1

Try to use jquery and document ready event:

$(document).ready(function(){
     if(document.getElementById("VARDIV")!==null)
     {
        alert('div exists!');
     }
})

If you do not want to include jquery js lib, you can use the solution here:

pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it

Community
  • 1
  • 1
Georgi Bilyukov
  • 645
  • 4
  • 11
1

Actually if you place the javascript code at the end of file after all php and html code it must work.I have tested it.

<?php if(isset($_GET['VAR']))
{
   echo '<div id="VARDIV">Dilip</div>';
}?>

<script type="text/javascript">
    if(document.getElementById("VARDIV")!==null)
{
     alert('div exists!');
}
</script>

but i think it is better to use onload event

window.onload=function(){if(document.getElementById("VARDIV")!==null)
    {
         alert('div exists!');
    }};

Or if you are ok to use jquery then its awesome..

$(document).ready(function(){
     if(document.getElementById("VARDIV")!==null)
     {
        alert('div exists!');
     }
})
g-newa
  • 459
  • 3
  • 10
  • Just as with Irossy's answer above, I totally understand now, but believe that things that rely on order of placement to execute correctly is just asking for trouble. Agree completely with the "onload" concept. Thank you! – dynamphorous Aug 19 '14 at 17:36
  • The interpreter executes the java script code as soon as it encounters it. so if you place script before the creation of div then obviously the problem occurs :) – g-newa Aug 19 '14 at 17:46
1

Any JavaScript that is not inside a function is executed sequentially as the page is interpreted. Your doDIVStuff(); call is executing before any HTML is interpreted on the page, therefore your "VARDIV" is not yet available in the DOM for the JS to read.

As others have suggested, the best approach is to listen for when the page is done loading and then trigger the call to your function.

Paul Zepernick
  • 1,452
  • 1
  • 11
  • 25
0

Wrap in doc rdy() or just do something like this:

<html>
<head>

</head>
<body>
<?php if(isset($_GET['VAR']))
{
  echo '<div id="VARDIV"></div>';
}?>
<script type="text/javascript">
  function doDIVStuff()
  {
    if(document.getElementById("VARDIV")!==null)
    {
      console.log('div exists!');
    }
  }
  doDIVStuff();
</script>
</body>

</html>
lrossy
  • 533
  • 3
  • 10
  • This seems dangerous based on what they said above. Trying to include things in a particular order that you want to execute in that exact order would get messy if you expected that behavior (as I did) even if you rearranged it. Code that relies on functions being placed in a given order to work correctly is too dangerous for production environments in my estimation. – dynamphorous Aug 19 '14 at 17:33
0

I'd say you should create a javascript file and put your code there so you can debug it.

megaKertz
  • 484
  • 6
  • 11