If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

How to use document.getElementById() with php?

How do I retrieve a php variable in JS? I tried using "document.getElementById()" but it always returns NULL. There must be something I don't understand from the instructions. I tried several variations.

I.e. if a php variable is named $test
what does the retrieval to JS look like?

You can not use JavaScript server-side, JavaScript is a client-side language.

You can use PHP to generate HTML and JavaScript code but not the other way around, not in the way you appear to be using it.

To retrieve data from a server using JavaScript you need to use what is referred to as AJAX which is Asynchronous Javascript And XML

To be very basic and rudimentary an AJAX routine consists of...

Code:

// we make an AJAX (aka XML) object
ajax = new XMLHttpRequest();
// we now make a request object
ajax.open("GET","yourScript.php",true);
// we now make reference to a method to handle the results (if any)
ajax.onreadystatechange = function(){
// test if the result has completed the request states
if( ajax.readyState == 4){
// we completed but was the result OK?
if(ajax.status == 200){
// we were OK because we had HTTP 200 signal
alert(ajax.responseText); // show the result
}
}
}
// now make the request
ajax.send();

Your receiving script yourScript.php will be any number of methods of returning information requested, it could be as simple as...

PHP Code:

echo date("r");

returning an RFC based time stamp

You can test this on your computer if you have a web server installed, or a service that will allow development testing on your PC, one word of advice is that you need and can't stress enough, to install a firewall, forget windows firewall as its about as useful as a chocolate tea pot.