I have an application that builds page content from multiple page fragments comprising the template page. One or more of these fragments need to run JavaScript when the document has loaded, and it does not make sense to put fragment specific code in the template page comprising the fragments. While this approach has worked out for me quite well, I have a problem when attempting to update a fragment via Ajax based on the user's interaction with the page.
I am using jQuery and $(document).ready(function() {...}); rather liberally, both in the template page (for globally scoped code) and the fragments (for fragment specific code). Problem is, when a fragment is updated using jQuery's .html(HTML code from Ajax response) on the jQuery enriched version of the HTML element and the Ajax response itself contains $(document).ready(function() {...}); code, the HTML content gets updated nicely but the JS does not execute.
Some suggest use of eval() on the JS fragments inside the Ajax response while others forbid it. I am hoping someone will push me in the right direction with this.
$.ajax({
type: 'POST',
url: $(formObj).attr('action'),
data: $(formObj).serialize(),
})
.done(function(data, textStatus, jqXHR) {
$response = $(data.replace(/<body(.*?)>/,'<body$1><div id="ajaxResBody">').replace('</body>','</div></body>'));
$('#fragmentContent').html($response.find('#fragmentContent').html());
});
<div id="fragmentContent">...</div> is one of the fragments updated using partial content extracted from the Ajax response. When the page is initially loaded, the fragment's content DOM looks approximately like this:
<div id="fragmentContent">
<p>...</p>
<div>...</div>
<script type="text/javascript">
$(document).ready(function() {
// JS code
});
</script>
</div>
But when the same fragment's content is replaced via Ajax, the DOM looks like this:
<div id="fragmentContent">
<p>...</p>
<div>...</div>
</div>
So it is quite apparent scripts are stripped. I verified that by using the following code:
if (data.indexOf('accordion(') >= 0) {
console.log('scripts found in Ajax response');
if ($response.find('#fragmentContent').html().indexOf('accordion(') >= 0) {
console.log('scripts inserted into fragment');
}
else {
console.log('scripts stripped before content inserted into fragment!');
}
}
else {
console.log('scripts did not even make it in the Ajax response!');
}
and the following log output was yielded:
scripts found in Ajax response
scripts stripped before content inserted into fragment!
Related
i am working on a single page application using jQuery. whole html pages are sent as response to browser as ajax response.
$.post(url, function (data) {
$("#resp").html(data);
$("#resp").find("script").each(function (i) {
//alert($(this).text());
eval($(this).text());
});
});
how to remove script tags from data and than assign html to the div ?
the issue i am facing is the scripts that are written in the response page. they were not getting added to the DOM at first, so i used eval(), now the scripts are getting added twice in some situations.
The easiest way would be to use the .load() function with a fragment selector, since that will strip out <script> tags prior to updating content and result in them not being executed. If you're working with entire HTML pages though there may not be a suitable selector for you to use. However, I'd suggest trying this first:
$('#resp').load(url + ' body');
That would give you just the content between the <body> and </body> tags in the HTML page requested via AJAX.
If that doesn't work, I guess you could try manually stripping out <script> tags from the response prior to adding to the DOM:
$.post(url, function(data) {
var tempDiv = $('<div>').html(data).find('script').remove();
$('#resp').html(tempDiv.html());
});
That creates a new <div> element that isn't part of the document, sets its HTML to the returned HTML from the AJAX request, searches for <script> elements inside that, and then removes them. However, even though the element isn't part of the current document yet, the scripts may still end up being executed (I've never had a reason to do this so I haven't tested it).
with the help of Anthony's answer this is what i did to get it working :
$.post(url, function (data) {
var tempDiv = $('<div>').html(data);
var raw = $('<div>').html(data);
$(tempDiv).find("script").remove();
$("#resp").html(tempDiv.html());
$(scripts).find("script").each(function (i) {
//alert($(this).text());
eval($(this).text());
});
});
i could not understand why
var tempDiv = $('<div>').html(data).find('script').remove();
did'nt work though.
I'm using the $.get() function to extract some data from my site. Everything works great however on one of the pages the information I need to extract is dynamically created and then inserted into a <div> tag.
So in the <script> tag, a function is run and then the data is inserted into <div id="infoContainer"></div>. I need to get the information from #infoContainer, however when I try to do so in the $.get() function, it just says it's empty. I have figured out that it is because the <script> tag is not being run. Is there another way to do this?
Edit:I am making a PhoneGap application for my site using jQuery to move content around so it's more streamlined for mobiles.
This is the code on my page:
$(document).ready(function () {
var embedTag = document.createElement("embed");
var infoContainer = document.getElementById("infoContainer");
if (infoContainer != null) {
embedTag.setAttribute("height", "139");
embedTag.setAttribute("width", "356");...other attributes
infoContainer.appendChild(embedTag);
});
});
As you can see, it puts content into the #infoContainer tag. However, when I try to extract info from that tag through the get function it shows it as empty.I have done the same to extract headings and it works great. All I can gather is the script tag is not firing.
This should provide you the contents of the element:
$('#infoContainer').html();
Maybe your script is executing before the DOM is loaded.
So if you are manipulating DOM elements you should wait till DOM is loaded to manipulate it. Alternately you can place your script tag at the end of your HTML document.
// These three are equivalent, choose one:
document.addEventListener('DOMContentLoaded', initializeOrWhatever);
$( initializeOrWhatever );
$.ready( initializeOrWhatever );
function initializeOrWhatever(){
// By the time this is called, the DOM is loaded and you can read/write to it
$.getJSON('/foo/', { myData: $('#myInput').val() }, onResponse);
function onResponse(res){
$(document).html('<h1>Hello '+res+'</h1>');
};
};
Otherwise... post more specifics and code
You have no ID to reference. Try setting one before you append
embedTag.setAttribute("id", "uniqueID");
It looks like you are wanting to use jQuery, but your example code has vanilla JavaScript. Your entire function can be simplified using the following jQuery (jsFiddle):
(function () {
var embedTag = $(document.createElement("embed"));
var infoContainer = $("#infoContainer");
if (infoContainer.length) {
embedTag.attr({"height": 139, "width": 356});
infoContainer.append(embedTag);
}
console.log(infoContainer.html()); // This gets you the contents of #infoContainer
})();
jQuery's .get() method is for sending GET requests to a server-side script. I don't think it does what you are wanting to do.
I'm using jquery's .html() function to inject a html file into a partial div of the main page of my application. In the injected partial html page, there is a javascript reference such as script(src='../../javascripts/partialFunctions.js').
The jquery function and the main page are like:
$('.partialDiv').html(htmlResult);
<div>main page</div>
<div class='partialDiv'></div>
<input type='button'>button</input>
When the user click a specific button on the main application page, the jquery function will got called and the html file will got injected to the main page.
The problem is every time a new htm file got injected, the browser will load the script file. So there will be many duplicated javascript functions after the user clicked the button several times.
How can I do this dynamically and avoid the duplication of javascript functions?
Thanks in advance!
You can remove the script tags and references from the htmlResult page.
Then use $.getScript('myscript.js') to import the necessary JavaScript files.
More info on getScript() here
So to load in the script and make sure it only loads in once:
var window.foo = false; //Outside the document.ready
$('.partialDiv').html(htmlResult);
if(window.foo == false){
$.getScript("js/myScript.js", function(data, textStatus, jqxhr){
console.log('Script loaded');
window.foo = true;
});
}
I just did a quick test, it looks like script tags are stripped out anyways when you call .html(). So you should be able to simply do:
var html = "<html><script></script></html>",
cleanedHtml = $(html).html();
myEl.html(cleanedHtml);
I am coding a big website but I have cut down my problem into the following tiny html file:
http://dl.dropbox.com/u/3224566/test.html
The problem is that if I (re)load with JQuery a content that features a facebook code, the latter won't appear, even if I reload the script (leading to a duplication of that all.js script, which is another issue).
How can I fix this?
Regards,
Quentin
Use the FB.XFBML.parse() docs after you load the new content
function loadPage() {
$('#test').load('test.html #test', function() {
FB.XFBML.parse( );
}).fadeOut('slow').fadeIn('slow');
}
Note, that loading a fragment with id test in a div with id test will create multiple (two) elements with the same id (nested in each other) in the page, which should never happen as it is invalid.
To avoid this use the more verbose $.get method
$.get('test.html',
function(data) {
var temp = $('<div>').html(data).find('#test');
$('#test').html(temp.html());
}
);
I am trying to call some script in a newly ajax loaded tab but it looks like the script blocks inside the tab are not being processed at all so when I go to call a function in the tab the function cannot be found. Is there a way to properly load the tab content such that the scripts are interpreted?
I have tried playing with the ajax options but that doesn't seem to help.
$("#tabs").tabs({
ajaxOptions: {
error: function (xhr, status, index, anchor) {
$(anchor.hash).html("This tab not yet built, sorry bub.");
},
dataType: 'html'
},
spinner: 'Loading tabs...',
});
In the tabs I have something like
<script type="text/javascript">
function SetupTab(){
alert('loaded');
}
</script>
but
$("#tabs").bind("tabsshow", function(event, ui){ SetupTab();});
cannot find SetupTab. Even if I allow the tab to load and then attempt to call SetupTab from firebug it can't be found.
if you try and bind any events/actions to a html element that does not exist yet i.e.
$(document).ready(function(){
//apply elemnt bindings here
});
when you do load the elements using ajax the elements will not take on the bindings you supplied on document ready because they did not exist at that point.
Add a call back to your ajax call to then bind any events/functions to ur new html elements, then this should work.
I think thats what you was reffering to.
EDIT: try this.
$("#tabs").bind("tabsshow", function(event, ui){ alert('loaded');});
EDIT AGAIN: you could try this.
make sure the page you are loading just contains the script itself and not the script tags and then use:
//lets say the data returned from your ajax call:
data = function SetupTab(){alert('loaded');}
eval(data);
then you could call that function no problem.
EDIT 3RD TIME: if you cant remove the script tags from the page your load you could regex the html. with this pattern.
pattern = /<script\b[^>]*>(.*?)</script>/i
urscript = data.match(pattern);
eval(urscript[1]);
this should work.
What you can do is also to detach your ajax call from the element (do just $.getScript for example).
Your loading tabs function should do something like this:
<div class="tabs" onclick="$.getScript('myScript.php?index='+$(this).index(#tabs"))">...
Then the server-side script should return something like this:
echo '
$("#tabs").eq('.$_GET['index'].')html("'.$myHTML.'");
/* Then the rest of your JS script (what you had in your HTML output) */
';