www.webdeveloper.com
Results 1 to 7 of 7

Thread: Cannot get JS content from AJAX page to load

  1. #1
    Join Date
    Oct 2008
    Posts
    14

    Cannot get JS content from AJAX page to load

    I have been searching online for hours, but it is possible I'm just not thinking of the correct keywords. I have included a basic illustration of the current setup (which does not work). The issue lies with the page that is the desired output. I have a far deeper issue which I have narrowed down to javascript on the final .asp page not loading at all.
    Illustration of Setup http://startuplink.com/ajaxissue.png (cannot insert images apparently, sorry)

    On default.asp, I am calling a function contained in 'ajax_call-contentselection.js'

    Code:
    <a onclick="func_displaycontents('restaurants'); return false">displayajaxcontent</a>
    Honestly, I don't believe the following piece of code (ajax_call-contentselection.js) is relevant, as it is standard ajax code, but just in case:
    Code:
    function func_displaycontents(var_type){     
    	var xmlHttp = GetXmlHttpObject();     
    	var url = "../_include/ajax_display-contentselection.asp";    
    	url += "?type="+var_type;
    
    	if (!xmlHttp){          
    		alert ("Browser does not support HTTP Request")          
    		return     
    	}    
    		
    	xmlHttp.onreadystatechange=function(){     
    	if(xmlHttp.readyState == 1){
           		document.getElementById("div_ajaxfillattractions").innerHTML = "<div style='padding-top:50px;color:white;width:930px;text-align:center;'><img src='../_images/ajax-loader.gif'/><br/>Loading...</div>";
    	};
    	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
    			document.getElementById("div_ajaxfillattractions").innerHTML=xmlHttp.responseText;
            	}     
    	};     
    	xmlHttp.open("GET", url, true);     
    	xmlHttp.send(null);
    }
    The other contents of "ajax_display-contentselection.asp" are displayed properly in "div_ajaxfillattractions" of "default.asp", but no javascript code on that page loads. If I use "ajax_display-contentselection.asp" as an include file on "default.asp", I get the javascript alert of 'Success', but when I initiate the AJAX it does not work, so I know there isn't a problem with the javascript.

    Please let me know if I sucked at explaining something, or more detail is needed.

    Thanks in advance,
    Matt

  2. #2
    Join Date
    Oct 2003
    Location
    Andover, UK
    Posts
    947
    I'm not sure I followed all that, but am I right in thinking you're wondering why Javascript put out by your ajax handler, and returned to the main page, isn't running? If so, that's because ajax returns the response as either text or as xml. If you want to return code, you'll need to eval() it when it reaches the callback function, i.e. the JSON approach.

    Not sure if I answered or even understood your problem, but I tried!

  3. #3
    Join Date
    Oct 2008
    Posts
    14
    mitya, it sounds like you understood correctly. Can you please give me a little more information? I will go on a Google-hunt for the information you provided, but I know jack about javascript, so my research efforts may be futile.

    On the page called by the AJAX code, I have the following JS elements that do not load when called.
    Code:
    <script type="text/javascript" src="_js/js_jquery.js"></script>
    <script type="text/javascript" src="_js/js_easySlider1.5.js"></script>
    If I simply view the page being called by itself, the javascript works fine, the problem only happens when I invoke the AJAX from the main page.

  4. #4
    Join Date
    Oct 2003
    Location
    Andover, UK
    Posts
    947
    Right OK - so the principle, as I said, is ajax can return only text or XML. You're returning as text, since you're using .responseText.

    That means if you want that text to be interpreted as javascript you need to evaluate it.

    This is fine for inline scripts but will not work for your <script src="... scripts. To my knowledge, there is no way to get them to work if they live in a page that is fetched via ajax.

    Assume we're fetching a page called somePage.htm via ajax. The content of somePage.htm is, say:

    Code:
    alert('hello, world');
    So let's fetch it:

    Code:
    //prepare ajax function
    function startAjax() { //appropriate to browser being used
        var xmlHttpObj;
        if (window.XMLHttpRequest)
        xmlHttpObj = new XMLHttpRequest();
        else {
            try { xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP"); }
            catch (e) {
                try { xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP"); }
                catch (e) { xmlHttpObj = false; }
            }
        }
        return xmlHttpObj;
    }
    
    //fetch our page, somePage.htm
    gateway = startAjax();
    gateway.open('GET', 'somePage.htm', true);
    gateway.onreadystatechange = processResponse;
    gateway.send(null);
    As you can see, I've said that, onreadystate change, JS should hit processResponse(). So here it is - note how we're eval()'ing the response. That means it will be interpreted as javascript and therefore the alert() will run.

    Code:
    function processResponse() {
    if (gateway.readyState == 4 && gateway.status == 200) { //response was received - let's process it
    	eval(gateway.responseText);
    }
    However, there are drawbacks to this.

    Since you're returning an entire page via ajax (not a good idea and not what ajax is meant for), that page will contain not only javascript but also html, meta data, etc etc.

    The above tells javascript to interpret the whole response as javascript. Since only some of the response is JS, it will error when it tries to interpret the rest of it as JS.

    You'll either need to make several ajax calls, to get the javascript separately from the rest of the page content, else string handle the response and find the bits of it that are javascript, and eval() just those (e.g. via a regular expression matching "<script"> and "</script>" tags).

    Either way, it's complicated.

    Moreover, it's generally a no-no to a gaping eval() on your page as it's open to abuse, depending on what it's evaluating.

    Hope this helps.
    Last edited by mitya; 12-09-2009 at 05:01 PM.

  5. #5
    Join Date
    Oct 2008
    Posts
    14
    Actually, that helps a lot. I have modified my architecture a bit. I was trying to put the non-inline javascript on the page to be returned to fix an issue I was having. In moving some things around (now that I understand how things work in this environment), I have resolved my original issue, so thank you very much.

    On the other hand, I've discovered a new issue, so I think I'll go sulk in a corner for a few hours

    Thanks,
    Matt

  6. #6
    Join Date
    Oct 2003
    Location
    Andover, UK
    Posts
    947
    No probs.

    If your new issue starts eating away at your brain, post it up and we'll try and help.

  7. #7
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    Quote Originally Posted by mitya View Post
    This is fine for inline scripts but will not work for your <script src="... scripts. To my knowledge, there is no way to get them to work if they live in a page that is fetched via ajax.
    you can ajax/eval each .src if it's local.
    or, you can use a dom-adder instead of <script src=xxx> tags:

    Code:
    <script>
     addJS("/includes/scripts/myFile.js");
    </script>
    in this fashion, auto-evaling the inline (see below for ideas) will add the scripts as expected, though you can't depend on variables being loaded, unless you craft a dependancy chain, use callbacks, or a load manager.

    here's the dom adder code:
    Code:
    function addJS(u){ 
      var sc2=document.createElement('script'); 
      sc2.src=u;  
      document.getElementsByTagName('*')[1].appendChild(sc2) 
    }
    also, instead of using regexps to find embedded script tags, i find it easier to eval() the source3 of the script after it's been added to the dom.

    something like:
    Code:
    var scripts=wrap.getElementsByTagName("script");
    for(var i=0, mx=scripts.length;i<mx;i++){
      var it=scripts[i];
      if(!it.src){eval(it.text||it.textContent||it.innerText||it.innerHTML);
    }
    you can also code a document-level dom mutation event to automatically look for and eval added script tags.

    as long as you use eval() on stuff from your site (which you pretty much have to), and you don't blindly re-server users content from other users, eval() is as safe as any other javascript function would be.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles