Results 1 to 4 of 4

Thread: How to use document.getElementById() with php?

  1. #1
    Join Date
    Nov 2013

    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?

  2. #2
    Join Date
    Mar 2007
    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...

    // we make an AJAX (aka XML) object
    ajax = new XMLHttpRequest();
    // we now make a request object
    // 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
    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.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  3. #3
    Join Date
    Oct 2013
    You can use php inside of javascript on the client side.

    So, as long as the variable $test is currently present somewhere on the page you could do...

    <script type="text/javascript">
    console.log(<?php $test ?>);
    This is done in wordpress files all the time.

  4. #4
    Join Date
    Oct 2013
    sorry, that should be <?php echo $test ?>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center