3

I have an index.php file that loads other php files via this javascript/ajax code:

function AJAX(elementID,url,showStatus){
var httpObject;
if (window.ActiveXObject) {
    httpObject = new ActiveXObject("Microsoft.XMLHTTP");
}
if (window.XMLHttpRequest){
    httpObject =  new XMLHttpRequest();
}
else {
    alert("Your browser does not support AJAX.");       
}

if (httpObject != null) {
    httpObject.onreadystatechange = function() {          
        if (elementID != false){                

            if (httpObject.readyState == 4 && httpObject.status == 200) {                  
                document.getElementById(elementID).innerHTML= httpObject.responseText;  

            } 
        }

    }

    httpObject.open("POST",url,true);
    httpObject.send(null);  
}
}

so for example I would load a file in inxex.php by:

<script>
AJAX("updateThisDiv", "/includes/contentpage.php", false)
</script>

which would paste the contents of "contentpage.php" into the div "updateThisDiv" but now if I have any javascript on "contentpage.php", it will not run, is there any way to do this?

I have looked at this: http://www.javascriptkit.com/script/script2/ajaxpagefetcher.shtml but its not exatcly what I was looking for.

I want to be able to update a section of my page without reloading the entire page and javascript must run

Jason Russell
  • 1,234
  • 3
  • 15
  • 27
  • Ive found this: http://stackoverflow.com/questions/4335142/why-would-php-generated-javascript-not-work-in-file-loaded-via-ajax but not sure what it is or how I would use it to get what I would like – Jason Russell Nov 11 '11 at 16:51
  • see if this helps http://stackoverflow.com/questions/4775444/can-xmlhttp-responsetext-contain-script-type-text-javascript-src-scrip – david Nov 11 '11 at 16:58
  • http://russell.selfip.net/test if you want to see an example of my problem – Jason Russell Nov 11 '11 at 16:59
  • You can use javascript to update the new div, after fetching it's contents through the AJAX call. I fail to see the problem here. – RHT Nov 11 '11 at 17:20
  • eval works, but now I cant see any of the original html, ill have to print it out with javascript – Jason Russell Nov 11 '11 at 17:20
  • @RHT I have javascript in the contents im fetching for the new div that I would like to run when I fetch – Jason Russell Nov 11 '11 at 17:23

3 Answers3

4

If you want to load Javascript on demand. This can be done by dynamically creating script tag. This pattern illustrated in Stoyan Stefanov book - Javascript Patterns

This snipped from the book:

Write a require function. Then call it like this:

require("extra.js", function () {
    functionDefinedInExtraJS();
});

Sample require function:

function require(file, callback) {

    var script = document.getElementsByTagName('script')[0],
        newjs = document.createElement('script');

    // IE
    newjs.onreadystatechange = function () {
        if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
            callback();
        }
    };

    // others
    newjs.onload = function () {
        callback();
    };
    
    newjs.src = file;
    script.parentNode.insertBefore(newjs, script);
}

Live example found in http://www.jspatterns.com/book/8/ondemand.html

@Edit: more details specific to your case. I will try to make things simple:

Create four files:

  • index.php : the test file.
  • code.js : actual code which have Ajax, getJS, getHTML functions
  • content.php : any PHP file that will print pure HTML without any JS
  • content.js : javascript code that you want to run dynamically.

index.php

<html>
    <head>
        <script src="code.js"></script>
    </head>
    <body>
        <input type="button" onclick="Ajax('content.php', 'd_html');" value="Fill from content.php"/>
        <div id="d_html"></div>
        <br>
        <input type="button" onclick="Ajax('content.js', 'd_js');" value="Fill from content.js"/>
        <div id="d_js"></div>
    </body>
</html>

content.php

<span>Hello, I am dynamic span came from content.php</span>

content.js

//Ana javascript code you want to run it by Ajax function should go inside this function
function executeJS(element){
   element.innerHTML = "<span>Hello, I am dynamic span came from content.js</span>";
}

code.js

//This function responsible for doing the ajax request for any file that will return pure HTML.
function getHTML(url, element){
    var i, xhr, activeXids = [
        'MSXML2.XMLHTTP.3.0',
        'MSXML2.XMLHTTP',
        'Microsoft.XMLHTTP'
    ];

    if (typeof XMLHttpRequest === "function") { // native XHR
        xhr =  new XMLHttpRequest();        
    } else { // IE before 7
        for (i = 0; i < activeXids.length; i += 1) {
            try {
                xhr = new ActiveXObject(activeXids[i]);
                break;
            } catch (e) {}
        }
    }

    xhr.onreadystatechange = function () {
        if (xhr.readyState !== 4) {
            return false;
        }
        if (xhr.status !== 200) {
            alert("Error, status code: " + xhr.status);
            return false;
        }
        
        element.innerHTML += xhr.responseText;
    };

    xhr.open("GET", url, true); 
    xhr.send("");
}

//This function will load javascript file on-demand and call executeJS function inside that file.
function getJS(url, element, cb){
    var newjs = document.createElement('script');
    
    // IE
    newjs.onreadystatechange = function () {
        if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
            cb();
        }
    };

    // others
    newjs.onload = function () {
        cb();
    };
    
    newjs.src = url;
    element.appendChild(newjs);
}


//This is same as your function, but now can handle both PHP and JS files
function Ajax(url, id){
    var element = document.getElementById(id),
        regex = /\.js$/;
    if(!element){
        alert("Invalid ID");
        return false;
    }

    if(regex.test(url)){ //If url ends with JS, load using getJS
        getJS(url, element, function(){
            executeJS(element);
        });
    } else {
        getHTML(url, element);
    }
}
Ted
  • 3,805
  • 14
  • 56
  • 98
Laith Shadeed
  • 4,271
  • 2
  • 23
  • 27
2

If you dynamically insert a script tag the code will execute. DO NOT USE EVAL. Libraries know this, they don't use eval either (unless they're terrible).

AutoSponge
  • 1,444
  • 10
  • 7
  • 1
    I have inside the php file that Im loading via my ajax script and it wont print out the time, like it does if I browse directly to the php page with this on it – Jason Russell Nov 11 '11 at 16:57
  • @JasonRussell Laith Shadeed has provided an example what AutoSponge suggests – david Nov 11 '11 at 17:10
  • Render to DOM, query scripts, create new scripts, then attach those to head. See https://stackoverflow.com/a/25406725/4907950 – Justin Mar 03 '23 at 19:07
1

this works 100%.....but I would prefer to not use jquery

<!DOCTYPE html>
<html dir=”ltr” lang=”en-US”>
<head>
    <meta charset=”UTF-8” />
    <title>AJAX Detection And Data Loading Using New School jQuery & HTML5:</title>            
    <script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js” 
type=”text/javascript”></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("button").click(function () {
                $("#mm").load("test.php");
            });
        });
    </script>
</head>
<body>
    <button type=”button”>Load Some Copy!</button>
    <div id="mm">
    </div>
    <section>
    </section>
</body>
</html>
Jason Russell
  • 1,234
  • 3
  • 15
  • 27
  • What would you prefer instead of using jQuery? –  Nov 17 '11 at 17:56
  • Id rather have my own method or function I need to do this: evalJS (Boolean | String; default true): Automatically evals the content of Ajax.Response#responseText and populates Ajax.Response#responseJSON with it if the Content-type returned by the server is set to application/json. If the request doesn't obey same-origin policy, the content is sanitized before evaluation. If you need to force evalutation, pass 'force'. To prevent it altogether, pass false.http://api.prototypejs.org/ajax/ – Jason Russell Nov 18 '11 at 21:26