views:

164

answers:

2

Difficult to explain this Question, but im currently passing variables in a php page to some html hidden inputs.

Im fetching those values from the hidden inputs with a javascript function. This function gets called like this:

 <body onload="function();">

It works on my system now, but is there any chance that the value passed from php might not get through because body has called the function BEFORE the php code sets the input type hidden?

Thanks

+8  A: 

You have may have mixed up which part does what.

  • PHP generates the HTML page on the server side. When the HTML page arrives at the browser, PHP has done its job. There is no way for PHP to do something after it has rendered the HTML.

  • Javascript is executed in the user's browser after the page has been generated and loaded. (Or during; as theraccoonbear points out, Javasript can run in the browser before the page has loaded completely.)

  • A Javascript command can not communicate with the PHP script rendering the page, because when Javascript comes into play, PHP is already gone.

So the answer to your question is: No, the JS function can not execute before PHP is done. As several commentators point out, that is not entirely true. A Javascript could come into action before the input HTML elements have been rendered. In your example however, the Javascript triggers only when the document is completely loaded. In that constellation, the answer is no, it can't happen.

Pekka
Javascript can begin executing before a page is completely loaded/parsed. if not, how do you explain nearly every JS framework's DOM ready functionality?i.e. (jQuery)$(document).ready(function() { ... });
theraccoonbear
theraccoonbear: Edited my answer to point out your point.
Pekka
He said the PHP generates hidden inputs that the Javascript reads from. He doesn't appear to be having any problem — just wanted to confirm that things will always run in the order they do on his system, which they will.
Chuck
Actually, on a slow connection, the browser could execute the onLoad function prior to the page being completely rendered. To prevent those, you really need some like... well... benlumley's answer.
R. Bemrose
Do you have some reading on the issue? It was always my understanding that onload fires when the whole page *and* all resources are loaded. Are there exceptions to that?
Pekka
+2  A: 

That shouldn't be an issue, as you are using the body's onload property, which will ensure the dom and all images etc have loaded.

Using jQuery to it like below would be better in my opinion, fires as soon as the dom is ready, rather than waiting for all images etc.

$(document).ready(function() {
    // do stuff here
});

This is also easily done from an external JS file if required, which helps you logically separate your code.

benlumley