Javascript doesn't load after AJAX call - javascript

Ok the following HTML code is parsed when I load a page:
<div id="clip-wrapper">
<script type="text/javascript">
alert("bla");
</script>
</div>
This obviously leads to an alert saying "bla", after my AJAX call, the parsed HTML code looks like this:
<div id="clip-wrapper">
<script type="text/javascript">
alert("ajaxbla");
</script>
</div>
This on the other hand, doesn't result in an alert. Why? And how do I fix this?

If there are any scripts loaded into your dom from an Ajax call, they will not be executed for security reasons.
To get the script to execute, you'll need to strip it out of the response, and run it through eval
Ideally though, you'll want to run your script as a callback for when your ajax request completes. If you're using jQuery, this would be the success event of your ajax call, and if you're doing it natively, it would be the readyStateChange event of your xhr object.
EDIT
If you really want to opt for the eval option, you could try something like this:
document.getElementById(contentDiv).innerHTML = xmlHttp.responseText;
eval(document.getElementById("clip-wrapper").innerHTML);

put you code in
$(document).ready(function()
{
alert(msg);
});
or make use of readysatchange event of XMLHttp object.
XMLHttpobject.readyStateChange( furnction() { alert('msg'); } );
Edit
if you are using jquery than go for
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
here in sucess event you can write your code which get executed once you are done with the ajax.

any code inside body in between script tag will executed only while loading the document.
in ajax call,make use of callback or success: or oncomplete: to handle the ajax response if you are using jQuery.

You mean the second html code is coming as an ajax response?? Did you even inserted the html to the current page?
Something like,
document.body.innerHTML = ajax_response;
But even with innerHTML replacement I don't thing the script inside it will be auto executed. The browser will parse the script but won't auto execute it. (For eg, if you have a function definition in the html, after the ajax call you will be able to call those functions)
Another option is to use document.write, it will replace the whole page content with the new html and the script tags in it will be auto executed.
document.write(ajax_response);
Hope this helps,

Related

modify CSS of elements created via .load()

First time using jQuery. I'm using it to load the content of an external element onto my page. It loads fine, but I'm finding that the normal traversal methods don't work on the loaded elements. For instance, what I have is:
<div id="area"></div>
<script type="text/javascript">
$("#area").load("externalPage.html #externalElement > *");
$("#area").find("ul").first().css("display","none");
</script>
The second line of the script appears to do nothing. Does this have something to do with the order in which operations are completed?
I'm loading this into a custom HTML module on the Blackboard LMS, which can sometimes behave strangely if scripting gets too complicated, so this could very well be another one of those times. Thank you for helping me figure it out!
The call to load() is asynchronous. This means that your find() is being run before the request completes and the elements are created in the DOM.
To workaround this you can put your logic in the callback parameter of load(). This means that it will not be called until the request completes and the DOM is in the state you expect. Try this:
$("#area").load("externalPage.html #externalElement > *", function() {
$("#area").find("ul").first().css("display","none");
});
.load() has a callback for when it's done. You can do what you want to the new markup in there.
$("#area").load('foo.html', function () {
/* Now you have access to foo.html's markup */
});
You need to put that second line in the callback to .load():
$("#area").load("externalPage.html #externalElement > *", function() {
$("#area").find("ul").first().css("display","none");
});
Things like $.get() and $.fn.load() are convenience functions built on the basic jQuery $.ajax() system. The process of loading content is inherently asynchronous.

AJAX that calls a "parent" function

I've seen a few questions like the one I'll ask but nothing identical. I have two html files, main and today. What I want to do is load today.html via AJAX into a child div in main.html. Sometime after load, I would like to call a function that resides in main.html from today.html
Within Main I have this function:
function drawCircle (size){
alert('DRAWING');
}
This AJAX load:
$("#leftofad").ajax({
url: ":Today.html?r="+genRand(),
type: 'GET',
success: function(data) { },
error: function() { alert('Failed!'); },
});
And this div:
<div id="leftofad"></div>
In Today.html I have
<script type="text/javascript">
$(document).ready(function(){
drawCircle (100);
});
</script>
The load is going well but Today.html doesnt seem to recognize the drawCircle function. I've tried several precursors including this., window., and parent..
I understand that I can use the callback method of the AJAX loader in jQuery but I don't necessarily want to call drawCircle when the load is complete. I may want to wait a bit or do it as a result of an action from the user. Is it possible to reference these functions from an AJAX-loaded div? If not, can I use an alternative method like events and listeners to fire the drawCircle function?
Since you will be loading JS into your page, try calling the function directly?
(The ready function won't run as the main page is already loaded)
Main.html
<script type="text/javascript">
function drawCircle(size) { alert("DRAWING" + size); }
$(function() {
$("#leftofad").load("Today.html?r="+genRand(), function() {
alert('loaded successfully!');
});
});
</script>
<div id="leftofad"></div>
Today.html
<script type="text/javascript">
drawCircle(100);
</script>
If this doesn't work, I strongly suspect that JavaScript returned in an AJAX call is not executed.
In this case, refer to: How to execute javascript inside a script tag returned by an ajax response
$("#leftofad").ajax is not proper.
jQuery's $.ajax function does not use a selector.
What you can use is load:
$("#leftofad").load("Today.html?r="+genRand(), function(){
alert('loaded successfully!');
});
Everyone here has some good answers, but I believe there is a knowledge gap and we are missing some information. If I were you, I would add an alert to the script in the Today.html file right before the drawCirle. Then I would run this page using IE or Chrome dev tools or Firebug in Firefox. When the alert is displayed you can put a breakpoint in the javascript code. Then check your global scope to try and locate drawCirle...
Sorry this is not an exact answer, but with javascript files you need to use debugging tools for this.
while there isn't really a document.ready function for a div, there is a hack that works just as if so:
create your returning data as a full html page:
<html>
<head>
<script type='text/javascript'>
$(document).ready( function () {
do-this;
to-that;
....
});
</script>
</head>
<body>
<%
your possible vbscript
%>
the rest of stuff to be loaded into that div
</body>
</html>
Then, you can have as many cascading div loading from different page loading and .... rinse and repeat ... forever .... EXPERIMENT with different DOCTYPE to see the different results.
EDIT:
Then, of course, you load the original MAIN with
$('#thedivid').load('url-of-the-html-returning-page');
Which, in turn, can have the VERY SAME call in the returning page document.ready as, for example; $('#thedivid-inthereturningdata-html-page').load('url-of-the-html-of-the-child-process-for-whaterver); .... and so on.
Go ahead, PLAY AROUND and make wonderful ajax based applications ....

How do I execute inline javascript in HTML returned from an ajax call - JQUERY

very often I need to run some javascript on HTML contents returned from an ajax call. Just dumping it in a div doesn't seem to work. Whats the best way to do it? LIke lets say I return teh following HTML code:
<div><input type="text" id="someID" /></div>
<script language="javascript">
$('#someID').somefunction();
</script>
You should be using success event handlers. For example if you were using load() you'd do something like:
$('#foo').load('/my/ajax/stuff', function() {
$('#someID').somefunction();
});
For setting up form elements I generally create a setup function and call it on ready and ajax complete
function setup_form() {
$('.date-picker').datepicker();
}
$(setup_form);
$.ajaxComplete(setup_form);
This will now setup your form elements on document.ready as well as when an ajax request completes.

Will these ajax calls delay page elements further down?

I am using this pseudocode to retrieve some json files and put their content into the content div.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<title>Test</title>
</head>
<body>
<div id="content"></div>
<script type="text/javascript" charset="utf-8">
var my_files = ['http://example.com/file.json', 'http://example.com/file2.json'];
var params = {
format: 'json'
};
function _populate_content(arg){jQuery("#content").text(arg)}
jQuery(my_files.each(function() {
jQuery.ajax({
url: url,
dataType: 'jsonp',
data: params,
jsonpCallback: "_populate_content",
});
});
</script>
<div id="more_content"></div>
</body>
</html>
It might take some time to retrieve the remote files. My question is: Will this code delay the loading and rendering of the "more_content"-div?
Would it be better to enclose the ajax retrieval in a $(document).ready() block?
Will this code delay the loading and rendering of the "more_content"-div?
No, because the Ajax call is asynchronous (not blocking).
Would it be better to enclose the ajax retrieval in a $(document).ready() block?
Yes. This will execute the Ajax call once the whole DOM is rendered.
While it might work without, you cannot be 100% sure that element with ID content is available when the Ajax call returns. As #BiAiB pointed out, the element will be available. It is still good practice though.
Btw, if you want your code to work in all browsers, you should use jQuery's each and not the built-in one:
jQuery.each(my_files, function() {
jQuery.ajax({
url: url,
dataType: 'jsonp',
data: params,
jsonpCallback: "_populate_content",
});
});
Maybe this is only a stripped down example, but does it make sense to load both URLs? The second call will override the results of the first one...
Short answer: no. Since you haven't defined 'async:false' in the .ajax() parameters, the javascript will execute asynchronously. This means that your my_files array will loop through and fire off asynchronous calls then continue on loading the page.
You may want to wrap your logic in $(document).ready(), but before doing that place a throbber in your more_content div to let the user know information is coming shortly.
ajax calls are made asynchronous (unless you specify otherwise). So it won't delay your page loading.
the ajax call is asynchronus, so no delay.
if you put it into a document ready block,
you enshure that the browser did render the whole page before doing the call ..
Yes. The browser will block while those calls are made. You should instead do the work on page load so that the page is visible/rendered while the work is being done:
$(document).ready(function() {
jQuery(my_files.each(function() {
// etc...
}));
});

Loading Documents With Scripts in Ajax Tab

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) */
';

Categories