2

I have a really simple ajax script for loading HTML files into a div. The script looks like:

<head>
<script>
function fetchResults(){
/*$(document).ready(function() {*/
                $('#slideshow').cycle({
                fx: 'fade',
                pager: '#smallnav', 
                pause:   1, 
                speed: 1800,
                timeout:  3500 
            });         
        });
</script>
<script type="text/javascript">

var bustcachevar=1 (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
}

function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){
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+" " 
}
}
}

</script>
</head>

Which loads said HTML file neatly into this div:

 <div id="rss">
<script type="text/javascript">
            ajaxpage('news.html', 'content');   
        </script>
</div>

But on one of these HTML files, I have a tiny bit of javascript that won't load in the div, but loads fine when viewing the page directly.

<script src="http://feeds.feedburner.com/xxx/QFMN?format=sigpro" type="text/javascript" ></script>

I know there's an issue with javascript in ajax, but also know there's a work-around. Being a noob to javascript, I'm not completely sure how to work this. Any suggestions?

4
  • 3
    Proper indenting would be really helpful. Commented Feb 1, 2013 at 21:50
  • 2
    Your document ready event declaration line is commented out. Commented Feb 1, 2013 at 21:57
  • I found two errors in your JavaScript /*$(document).ready(function() {*/ and var bustcachevar=1 (1=yes, 0=no) .After that I stopped looking. Commented Feb 1, 2013 at 22:02
  • I understand the errors and improper indenting. My point being, I'm fairly new to this and trying to learn what another option for pulling this html file into this div is. Would doing this in jquery be a solution? Commented Feb 6, 2013 at 20:19

2 Answers 2

2

As you're already seem to be using jQuery, please, please, please use jQuery's Ajax methods to do asynchronous requests. All your code can be replaced with something like

$(function () {
    $('#container').html($.get('/some/other/url.html'));
});

Here's an example of a link, clicking on which replaces the contents of a div with the result of an AJAX call:

<a class="ajaxLink" href="/some/other/url.html">next</a>
<div id="container">
    Hello there
</div>

<script type="text/javascript">
    $(function () {
        $("a.ajaxLink").click(function () {
            $('#container').load($(this).attr('href'));
            return false;
        });
    });
</script>

Note how we cleverly using the href attribute of the link to specify the URL - if the client does not have JavaScript enabled the link will just work as usual.

JQuery documentation on AJAX methods is a valuable source of information. See "loading page fragments" and "script execution" in the documentation of the .load() method for explanation how scripts in the loaded pages are executed.

(also, using jslint or a similar service is immensely helpful)

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

5 Comments

This appears to be the most viable method, but I guess I'm not sure how this is implemented into the menu or div. Input?
I've updated the answer. If your problem is solved consider marking one of the answers as accepted.
I see what you're getting at, but Im trying to get these individual html files to load into a div. My problem lies in that I have a script on one page that won't return results because its in an ajax div.
@Catera: From the documentation it's not clear what's JQuery behaviour for scripts linked via <script src="..." />, as in your question - it may be possible that they're just discarded. There's a separate jQuery function to load a .js file though - api.jquery.com/jQuery.getScript - try loading your html and then calling the getScript function to load the js file
man I appreciate your help on this. It looks viable, But I have no idea where to start implementing this.
0

In fact,

you can't execute a Javascript coming from an ajax call. You can either do an eval(result) if result is pure javascript, or get the data out of your result by using some jquery like selector.

The main problem is that you shouldn't export your data as html but in JSON or XML

Your code could look like this:

$.ajax({
  url: "url",
  type: "GET",
  datatype: "xml",
  cache: false,
  success: function(response) {
    alert($("Result",response).text())
    eval($("Code",response).text())
  }
});

with this output:

<?xml version='1.0' encoding='UTF-8'?> <Result>Hi</Result> <Code>console.log(1)</Code>

This code will alert Hi and execute the code console.log(1)

4 Comments

I'm not sure "you can't execute a Javascript coming from an ajax call" claim is correct. If you load a normal html document with script tags using $.load, the code will be executed although the tags are discarded
"you can't execute a Javascript coming from an ajax call." So I find out. My next question, I was looking at the eval, but am not sure how I'd code that in. Any suggestions?
I'm not sure I understood your question. To use eval, you have to pass it some Javascript code in a string, like for example eval("alert(1)")
LOL GAWD, Im so lost with this stuff. A java script within an ajax call just doesn't seem to work. I tried the previous solution you gave, while lighter weight, it doesn't seem to solve my problem. @edi9999 Im not going to worry about the eval, it isn't a viable solution. Problem is I need it output in some sort of stylable text. Only thing I know of to do that is html.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.