0

Ok I have these two working code files so I decided to add JavaScript on a page call x.html so I expected the JavaScript to run after I push the AJAX button that is located in a page call index.html so everything executes but no JavaScript is executed on x.html just the HTML is executed.

So I read you have to use eval() to make AJAX notice and execute the JavaScript on the other page that it is calling AKA x.html.

.gif screenshot

Here's the code

index.html

<script>
var xhr= new XMLHttpRequest();
xhr.onreadystatechange= function(){
    if(xhr.readyState === 4){
        document.getElementById('ajax').innerHTML= xhr.responseText;
    }
};
xhr.open('POST','x.html');

function startAjax(){
    xhr.send();
document.getElementById('hide_button').style.display= 'none';
    }
    </script>
    <body>
    <button id='hide_button' onclick='startAjax()'>Start</button>
    <div id='ajax'></div>
    </body>

x.html

<!DOCTYPE html>
<html>
<head>
<script>
alert('hello');
</script>
</head>
<body>
<h1>Radom text</h1>
</body>
</html>
Joe
  • 41,484
  • 20
  • 104
  • 125
  • Can you use jQuery? Its `.html()` method will do what you want. – Barmar Jan 06 '18 at 01:41
  • If not, you need to do what jQuery does -- it parses the HTML, looking for ` – Barmar Jan 06 '18 at 01:43
  • Thanks barmar for your response I enjoy your posts I'm a big fan of your info well I know how to do this in jQuery. I'm just interested how this can be done in plain JavaScript. –  Jan 06 '18 at 01:44
  • There are many possible solutions here: https://stackoverflow.com/questions/1197575/can-scripts-be-inserted-with-innerhtml?noredirect=1&lq=1 – Barmar Jan 06 '18 at 01:45
  • I seen that link before but what if I want to call a html page that contains JS, Then how is that done? –  Jan 06 '18 at 01:47
  • I know my example is a php file but i'm treating it as html page. –  Jan 06 '18 at 01:48
  • Because I was in a hurry lol –  Jan 06 '18 at 01:48
  • The fact that its PHP is totally irrelevant. The browser just processes the HTML that it returns. – Barmar Jan 06 '18 at 01:48
  • Did you see this answer: https://stackoverflow.com/a/20584396/1491895 – Barmar Jan 06 '18 at 01:50
  • Well i'm not executing any php so it should act very similar to a HTML page if i'm not adding any PHP like I said I was in a hurry to ask this question. –  Jan 06 '18 at 01:51
  • Why you would execute `javascript` from `x.php`, you can just move your `alert('hello')` to `index.php` and run it just after ajax complete – YouneL Jan 06 '18 at 01:51
  • @YouneL The point is that the AJAX request can return different scripts, it's not always `alert('hello')`. – Barmar Jan 06 '18 at 01:52
  • @jdjones HTML vs PHP is totally irrelevant. – Barmar Jan 06 '18 at 01:52
  • @YouneL I am aware of that but for the purpose of simplicity I provided this example like this on here. So people will know what i'm talking about. –  Jan 06 '18 at 01:53
  • @Barmar It would not make any difference if the webpage extension was PHP or HTML if I was planing not planing to add any PHP code. If I did add PHP code then that will be a different story I tried this with the extension of HTML and it still give me the same results I am aware that PHP is a server language and HTML is a structural markup let's not focus on something that is off topic. Perhaps I should edit my post and not mention PHP. To avoid off topic conversation I'm focusing how this can be done in general. –  Jan 06 '18 at 01:58
  • As far as executing the Javascript is concerned, it doesn't matter how the content is generated. The browser doesn't know anything about what's going on on the server, and doesn't care, it just sees the result. – Barmar Jan 06 '18 at 02:03
  • There's nothing in the question I referred you to that's dependent on PHP, so I don't know why you brought it up. What's wrong with the answer I showed you? – Barmar Jan 06 '18 at 02:04
  • Well I just removed any mention of PHP from the post to avoid off topic conversations. Sorry @Barmar I was in a hurry to ask this question. And well I'm just curious how this can be done in plain JS I know how to do this with jQuery but I i'm just interested how this can be done in plain JavaScript. And well that link is confusing man almost every one suggested that and I don't want to call a pure js file or code I want to have AJAX to call a html page that contains JS. I'm just curious why this is difficult to do with just plain js. With jQuery this is easily done why so hard to do in JS? –  Jan 06 '18 at 02:11

3 Answers3

0

How about putting text into an iframe?

var idocument = $('iframe').prop('contentWindow').document;
idocument.body.innerHTML = xPhpText;
亚里士朱德
  • 510
  • 5
  • 15
0
evalScripts = function (elm) {
    var scripts =  elm.querySelectorAll('script');
    var allScriptsText = '';
    for (var i = 0; i < scripts.length; i++) {
        if (scripts[i].hasAttribute("src")) { 
            // reapend script tag for execution of remote content
             var s = scripts[i], p = s.parentElement;
                 p.removeChild(elm);
                 p.appendChild(elm)
        }
        allScriptsText +=  scripts[i].innerHTML + ";";
    }
    // evaluate inline scripts
    allScriptsText.trim() && setTimeout(new Function(allScriptsText), 0);
};

Now in your code use

xhr.onreadystatechange= function(){
   if(xhr.readyState === 4){
       var elm  = document.getElementById('ajax');
           elm.innerHTML= xhr.responseText;
           evalScripts(elm);

   }
};
bortunac
  • 4,642
  • 1
  • 32
  • 21
0

I figured this out this time. @Barmar express to me the cons of the last code solution I provided recently. I found a way to have AJAX execute JS in another page but @Barmar told me the way I had it recently will result only having one script tag set being able to be executed.

So I found a way to have this to work with more than one set of script tags. So here is the solution that works for me.

index.html

 <script>
    var xhr= new XMLHttpRequest();
    xhr.onreadystatechange= function() {
        if(xhr.readyState === 4) {
            document.getElementById('ajax').innerHTML= xhr.responseText;
            // get every <script>
            var exJs = document.getElementsByTagName('script');
            var enableAll = null;
            for (var i = 0; i < exJs.length; i++) {
                // add the <script> contents into enableAll variable
                enableAll += exJs[i].innerHTML;
            }
            eval(enableAll); // eval enables js to be read on the other page
        }
    };

    xhr.open('POST','x.html');
    function sendAjax(){
        xhr.send();
        document.getElementById('hide').style.display= 'none';
    }
    </script>
    <button id='hide' onclick='sendAjax()'>Go</button>
    <div id='ajax'></div>

x.html

<!DOCTYPE html>
<html>
<head>
<script>
alert('hello');
</script>
<script>
alert('hello again');
</script>
</head>
<body>
<h1>Random text</h1>
</body>
</html>
halfer
  • 19,824
  • 17
  • 99
  • 186
  • Using `[0]` means you'll only execute the first script in the HTML, not all of it. You should find all of the script tags and loop through them. – Barmar Jan 06 '18 at 03:00
  • I see what you mean how would you target all the script tags @Barmar? –  Jan 06 '18 at 05:00
  • Put `document.getElementById('ajax').getElementsByTagName('script')` in a variable, then use a `for` loop to iterate over it. Also, why do you need `setTimeout()`? – Barmar Jan 06 '18 at 17:36
  • The guy that helped me did that not me and ok i'm ma try to figure this out then i'll be back with a report. –  Jan 06 '18 at 19:52