1

I have this JavaScript:

<script>
    if (str == "") {
        document.getElementById("txtHint1").innerHTML = "";
        return;
    } else {
        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 (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint1").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET", "/npsmart/umts/action_plano/?q=" + query1, true);
        xmlhttp.send();

    }
</script> 

And this JavaScript call a page called getuser.php.

This is the code of getuser.php:

<!DOCTYPE html>
<html>
    <body>
        <p id="dumb"></p>
        <script>
            document.getElementById("dumb").innerHTML = "WORK";
        </script>
    </body>
</html>

What I would like is only to change the paragraph content, called dumb, to WORK. But when I call the page and it loads, my paragraph content keep null. It's like my Ajax Call Request don't execute the Script Tag.

EDIT:

I have already solved my problem with this simple but genious solution:

function showUser() {
if(query_num == 2){ 
if (str == "") {
    document.getElementById("txtHint1").innerHTML = "";
    return;
} else { 
    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 (this.readyState == 4 && this.status == 200) {
            document.getElementById("txtHint1").innerHTML = this.responseText;
            eval(document.getElementById("runscript").innerHTML);
        }
    };
    xmlhttp.open("GET","/npsmart/umts/action_plano/?q="+55555,true);
    xmlhttp.send();

}

And in my getuser.php file:

<script type="text/javascript" id="runscript">
document.getElementById("dumb").innerHTML = "WORK";
</script>

I just putted the : eval(document.getElementById("runscript").innerHTML); in my function and then in the php file I called this script using this:

<script type="text/javascript" id="runscript">

So thanks everybody =)

Hope this post can help other people.

1 Answers1

0

JS is not executed automatically from a script embedded in the response.

Since getuser.php is a PHP script there's no need to use JS and have the browser set the paragraph content. Use PHP itself:

<!DOCTYPE html>
<html>
    <body>
        <p id="dumb"><?php echo 'WORK'; /* or anything else */ ?></p>
    </body>
</html>

Otherwise you'll have to use JS eval on the returned AJAX response to have the browser run the JS returned from your script. But I recommend against this.

Matt S
  • 14,976
  • 6
  • 57
  • 76