0

I have seen other posts about echoing JS code, but it's not working for my JS code. I don't know if its because I'm echoing AJAX calls too, but I can't see why PHP would fuss about that.

What have I done wrong in echoing transforming these JS calls into its equivalent PHP calls?

JavaScript code:

    <script language="Javascript">
    var countdown;
    var i=0;
    countdown = setInterval(function(){
        var xmlhttp;
        if (window.XMLHttpRequest){
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }else{
            // code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                var JSONobj=JSON.parse(xmlhttp.responseText);
                document.getElementById("homelink").innerHTML=i;
                i++;
            }
        }
        xmlhttp.open("GET","updateindex.php",true);
        xmlhttp.send();
    },3000);
    </script>

PHP echo's for the above JavaScript code(what I need, but is not working):

    <?php
    echo "<script language='Javascript'>";
    echo "var countdown;";
    echo "var i=0;";
    echo "countdown = setInterval(function(){";
    echo "var xmlhttp;";
    echo "if (window.XMLHttpRequest){";
    echo "// code for IE7+, Firefox, Chrome, Opera, Safari";
    echo "xmlhttp=new XMLHttpRequest();";
    echo "}else{";
    echo "// code for IE6, IE5";
    echo "xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');";
    echo "}";
    echo "xmlhttp.onreadystatechange=function(){";
    echo "var JSONobj=JSON.parse(xmlhttp.responseText);";
    echo "document.getElementById('homelink').innerHTML=i;";
    echo "i++;";
    echo "}";
    echo "}";
    echo "xmlhttp.open('GET','updateindex.php',true);";
    echo "xmlhttp.send();";
    echo "},3000);";
    echo "</script>";
    ?>

My PHP code attempt above simply does nothing.

3
  • language='javascript' is deprecated, you should use type='text/javascript'. Commented Nov 30, 2013 at 23:26
  • 2
    Why don't you just close the php tag and put the javascript after that? Commented Nov 30, 2013 at 23:26
  • @WillHarrison depending on the DOCTYPE, you could drop all attrs from your script tag. Commented Nov 30, 2013 at 23:35

5 Answers 5

3

You are not echoing newline (\n) characters, so the entire output is one line of text.

In order for that to work, you need to be perfect in your JS syntax use of semi-colons, curly braces, etc. Furthermore, you are using single line comments (//) in this one resulting line of output. Once the first of those is hit by the parser, the rest of the line (which is the rest of your code) is a comment. Multi-line comment notation (/* comment */) would be preferred.

You need to add newline chars to the end of each echo'd line or use a heredoc or similar long-form string.

All that said, echoing JS like this is really bad practice. You should stop doing that. Closing PHP and reopening it when needed is good start. Moving the bulk of your JS to external JS files is better. If you need PHP to output data to JS, there are many other ways to accomplish it.

Addition from comments: You also have an extra echo "}"; line right before your echo "xmlhttp.open line. This sort of thing is common when trying to echo one lang from another, so it's one of the reasons I say you should stop.

Also, in your check for onreadystatechange you're not checking that the request had completed and was successful before you try to parse the response.

There may be other things wrong as well, but that's what I have so far.

Sign up to request clarification or add additional context in comments.

4 Comments

I need to execute JS code depending on a PHP condition, how else am I to do this?
See my edit to clarify for some options. Also, many people like to put values in hidden form fields which the JS then looks for. I like to write my JS in external libraries, then call a page-bootstrapping function at load, and inject all my PHP outputted data in one place as arguments.
Takeing out the commented lines completely and adding " \n" to the end of each echo doesn't work and still does nothing.
You also have an extra echo "}"; line right before your echo "xmlhttp.open line. Also, in your check for onreadystatechange you're not checking that the request had completed and was successful before you try to parse the response. There may be other things wrong as well, but that's what I have so far.
1

Try closing and reopening PHP tags:

?>
<script language="Javascript">
var countdown;
var i=0;
countdown = setInterval(function(){
    var xmlhttp;
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }else{
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            var JSONobj=JSON.parse(xmlhttp.responseText);
            document.getElementById("homelink").innerHTML=i;
            i++;
        }
    }
    xmlhttp.open("GET","updateindex.php",true);
    xmlhttp.send();
},3000);
</script>
<?php

This also gives you the luxury of highlighted code in the more simple IDEs/editors.

Comments

0

First, try to echo it this way:

<?php
echo '<script language="text/javascript">
    var countdown;
    var i=0;
    countdown = setInterval(function(){
        var xmlhttp;
        if (window.XMLHttpRequest){
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }else{
            // code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                var JSONobj=JSON.parse(xmlhttp.responseText);
                document.getElementById("homelink").innerHTML=i;
                i++;
            }
        }
        xmlhttp.open("GET","updateindex.php",true);
        xmlhttp.send();
    },3000);
    </script>';
?>

Check your page source if it really doesn't echo.

I just wanna add that it's pretty bad practice, but we're just trying to figure out why it doesn't work, not how to do it the best way...

Comments

0

You could make it easier for yourself by only echoing a function name. You could then reuse the code elsewhere. It would look something like this:

Javascript (in an external file maybe):

function someFunction(methode,url){
    var countdown;
    var i=0;
    countdown = setInterval(function(){
        var xmlhttp;
        if (window.XMLHttpRequest){
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }else{
            // code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                var JSONobj=JSON.parse(xmlhttp.responseText);
                document.getElementById("homelink").innerHTML=i;
                i++;
            }
        }
        xmlhttp.open(methode,url,true);
        xmlhttp.send();
    },3000);
}

PHP:

<?PHP echo '<script language="text/javascript"> someFunction("GET","updateindex.php"); </script>' ?>

Sidenote

The Chrome console and Firebug for Firefox are excellent tools for javascript debugging.

Comments

0

You not only echo the script, you have to invoke the script:

 echo '<script>
        (function(){
    var countdown;
var i=0;
countdown = setInterval(function(){
    var xmlhttp;
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }else{
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            var JSONobj=JSON.parse(xmlhttp.responseText);
            document.getElementById("homelink").innerHTML=i;
            i++;
        }
    }
    xmlhttp.open("GET","updateindex.php",true);
    xmlhttp.send();
},3000);


})();

</script>';


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.