PDA

View Full Version : Inserting a new javascript function in body from ajax request



crobinson42
03-18-2012, 10:36 PM
Hello,

I am loading a page via ajax request into a div, in the page loaded i have a new javascript function that i'd like to load and call on but it doesn't seem to work:

<script type="text/javascript">
function testFun(){
alert('Test Alert!');
}
</script>


When the above ^^ is loaded in the div from the ajax request I can't call on it... any ideas? (not working in IE of FF)

keyboard
03-18-2012, 10:53 PM
The alert works fine so it's a problem with the ajax. Could you please post the javascript (ajax) you are using to include the page.

crobinson42
03-18-2012, 11:17 PM
<script type="text/javascript">
function ajaxRequest(divTag,url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//loading animation
document.getElementById([divTag]).innerHTML="<image src=../images/loading.gif></img>";

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById([divTag]).innerHTML=xmlhttp.responseText;
parent.calcHeight();
}

}
xmlhttp.open("GET",[url],true);
xmlhttp.send();

}
</script>

molendijk
03-18-2012, 11:24 PM
Non-native code that is present in pages fetched via Ajax doesn't work (anymore) if Ajax uses innerHTML or its DOM-alternative(s). In that case, you have to bring in the code manually (to the parent page). Code is only preserved automatically if you use document.write, as in:

<script type="text/javascript">

function HttpRequest(url){
var pageRequest = false //variable to hold ajax object
/*@cc_on
@if (@_jscript_version >= 5)
try {
pageRequest = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try {
pageRequest = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e2){
pageRequest = false
}
}
@end

@*/ if (!pageRequest && typeof XMLHttpRequest != 'undefined')
pageRequest = new XMLHttpRequest()

if (pageRequest){ //if pageRequest is not false
pageRequest.open('GET', url, false) //get page synchronously
pageRequest.send(null)
document.write(pageRequest.responseText)

}
}
HttpRequest('page_you_want_to_include.html')
</script>
This is synchronous page-inclusion, but it works most of the time.
(keyboard1333, sorry to interrupt; I didn't see your comment when I posted my answer)
===
Arie Molendijk.