0

I'm loading my pages into divs with Ajax. Everything is fine, except I dont know how to eval the output so I can write javascript in the loaded pages. If anyone knows how, please tell me. tThanks!

This is my code:

var bustcachevar = 1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects = ""
var rootdomain = "http://" + window.location.hostname
var bustcacheparameter = ""

function ajaxpage(url, containerid) {
    var page_request = false
    if (window.XMLHttpRequest) // if Mozilla, Safari etc
    page_request = new XMLHttpRequest()
    else if (window.ActiveXObject) { // if IE
        try {
            page_request = new ActiveXObject("Msxml2.XMLHTTP")
        }
        catch (e) {
            try {
                page_request = new ActiveXObject("Microsoft.XMLHTTP")
            }
            catch (e) {}
        }
    }
    else return false page_request.onreadystatechange = function() {
        loadpage(page_request, containerid)
    }
    if (bustcachevar) //if bust caching of external page
    bustcacheparameter = (url.indexOf("?") != -1) ? "&" + new Date().getTime() : "?" + new Date().getTime()
    page_request.open('GET', url + bustcacheparameter, true)
    page_request.send(null)
}

function loadpage(page_request, containerid) {
    if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1)) document.getElementById(containerid).innerHTML = page_request.responseText eval(responseText);
}

function loadobjs() {
    if (!document.getElementById) return for (i = 0; i < arguments.length; i++) {
        var file = arguments[i]
        var fileref = ""
        if (loadedobjects.indexOf(file) == -1) { //Check to see if this object has not already been added to page before proceeding
            if (file.indexOf(".js") != -1) { //If object is a js file
                fileref = document.createElement('script')
                fileref.setAttribute("type", "text/javascript");
                fileref.setAttribute("src", file);
            }
            else if (file.indexOf(".css") != -1) { //If object is a css file
                fileref = document.createElement("link")
                fileref.setAttribute("rel", "stylesheet");
                fileref.setAttribute("type", "text/css");
                fileref.setAttribute("href", file);
            }
        }
        if (fileref != "") {
            document.getElementsByTagName("head").item(0).appendChild(fileref)
            loadedobjects += file + " " //Remember this object as being already added to page
        }
    }

}

RESPONSE TEXT:

        <div id="mySingleMenu"><?php include("single-menu.php"); ?></div>

        <div id="mySingleContent">
        <?php if (have_posts()) : ?>
            <?php while (have_posts()) : the_post(); ?>    

                <?php the_title(); ?>
                <?php the_excerpt(); ?>

            <?php endwhile; ?>     
        <?php endif; ?>
        </div>

    <script>
    $('#mySingleMenu').hide();

</script>

FIXED : http://www.javascriptkit.com/script/script2/ajaxpagefetcher.shtml

10
  • eval(page_request.responseText); Maybe? Eval doesn't work in IE7 ... i think Commented Aug 21, 2011 at 7:16
  • Where you've put eval(responseText);. Commented Aug 21, 2011 at 7:17
  • ah.. tried that yes, doesnt work :S Commented Aug 21, 2011 at 7:18
  • can you post the content of responseText? Commented Aug 21, 2011 at 7:28
  • 1
    Now that you posted the responseText, it's clear that you're not using JSON at all, so there's no need to bother with evaling anything. Just set the innerHTML = page_request.responseText and be done. Commented Aug 21, 2011 at 7:40

2 Answers 2

1

try this first..

insert the div into the page with an id that you control in js.. say id="1234" and then do the following.. note your script tag should be within this div

var d =
document.getElementById("1234").getElementsByTagName("script")
var t = d.length
for (var x=0;x<t;x++){
var newScript = document.createElement('script');
newScript.type = "text/javascript";
newScript.text = d[x].text;
document.getElementById('divContents').appendChild (newScript);  

else the apprach should be somewaht like below:

 // Suppose your response is a string:
// { html: "<p>add me to the page</p>, script:"alert('execute me');" }
var obj = eval( "(" + response + ")" ) ;
eval( obj.script ) ;

so you get the idea right you basically need to strip out the script part from the code and then eval it..

either that or you could use a library like jquery in which case all you need to do is use the html() api and it will take care of executing the script for you..

the other way is to insert the script onto the page you can do that in the ffollowing way:

var headID = document.getElementsByTagName("head")[0];         
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://www.somedomain.com/somescript.js';  //newScript.innerHTML= ""; //your script code
headID.appendChild(newScript);

there is a hack for this too. read this: http://www.thedanglybits.com/2007/06/22/execute-javascript-injected-using-innerhtml-attribute-even-with-safari/

Hope this helps..

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

7 Comments

if i add this code it doesnt show the ajaxpage nemore function loadpage(page_request, containerid){ if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)) var evalThis = eval('(' + responseText + ')'); eval( evalThis.script ) ; document.getElementById(containerid).innerHTML=page_request.responseText }
@Martijn: Stop thinking about eval(). You don't need eval to solve your problem. See sethobrien's comment to your question, that's the right direction.
it wnt work as it is.. you need to make sure that you are passing in only the script content to your eval.. that means the response shouldnt be xml it should be a json string parsed to json..
@tomalak "Script blocks inserted via innerHTML don't get executed in any browser other than NS6"
@martin I have edited the answer.. see the first part agian and try that
|
0

If you're getting properly formatted JSON back, then you'll want to use Douglas Crockford's JSON library: http://www.json.org/js.html

However... your entire code set is somewhat antiquated. There's a reason that the libraries have taken over, speeding development & reducing bugs.

In fact, here is all of your code, rewritten as jquery:

var bustcachevar = 1 //bust potential caching of external pages after initial request? (1=yes, 0=no) var loadedobjects = [];

function loadpage(page_request, containerid) {
    page_request = bustcachevar ? page_request + Math.rand() : page_request;
    $('#'+containerid).load(page_request);
    // This assumes what is coming back is HTML.  
    //If you're getting back JSON, you want this:
    // $.ajax({url:page_request, success:function(responseText){}}); }
    // Note that responseText is actually a pre-eval'd object.
function loadobjs() {
    if (!document.getElementById) return
    for (var i = 0; i < arguments.length; i++) {
        var file = arguments[i];
        var fileref = "";
        if ($.inArray(file, loadedobjects) < 0)
        {
            if (file.indexOf(".js") != -1) 
            { //If object is a js file
                fileref = $('<script>').attr('type', 'text/javascript').attr('src', file);
            } 
            else
            {
                fileref = $('<link>').attr('rel', 'stylesheet').attr('type', 'text/css').attr('href', file);
            }
            $('head').append(fileref);
            loadedobjects.push(file);
        }
    } 
}

Although you may not be familiar with the particulars of the syntax, you should see quickly that it is JS and its brevity should make it fairly easy to read. I was a POJ (plain-old-javascript) guy for years, but I just can't see any argument for it these days unless you're writing a serious library yourself (which I've also done).

5 Comments

Is the code "somewhat antiquated" or "wrong"? Because, if it's not wrong, there is no need to rewrite it as jQuery (and even if it contains a bug, there is no need to rewrite it as jQuery). I'm unable to see how that's helping.
First off, I answered his question directly. Secondly IMO, this is a forum for learning, not 'give me the right answer'. If I did that, then I'd just be encouraging a practice that I feel should be going away anyway.
thats ok, i want to learn ofc. i just need to go in the right direction.. the responsetext is html/javascript generated in wordpress, ive edited my original post with an example
Don't get me wrong, but you did not really answer his question. And how could you, he does not nearly give enough information for a definitive answer. You primarily rewrote his code into jQuery as if that alone already is a problem solver. Recommending jQuery upon every JavaScript question is a practice that I feel should go away.
I was working with the information I had at the time, which was that he was trying to eval text coming back through his response. And while it turns out that he wasn't trying to spit back javascript at all, I think it all sort of underscores the basic idea that POJ development is best left to the pros. But we get fairly religious fairly quickly. Coding comes down to choices more than anything else. I run a team of a dozen developers, and if any of them would choose to write the OP's code block above, they'd either get put into a corner or fired. This isn't 1998... there are better ways.

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.