JQuery, IE and Embedded javascript through AJAX

Last week I was working on a web page with several ajax calls. The process was something like this:
The first time the page loads it has some javascript in it. Then based on user's selection, some ajax calls would be made to the server and the server returns a block of page and that block would be inserted somewhere inside the html body. The returned block also has some javascript in it.
I wrote the page with php and ran it. It worked perfect with Firefox. But as soon as I tested it with IE, I saw the second scripts are not working. I checked the page with IEDeveloper toolbar and saw that the second scripts are not even in the DOM elements. With a little workaround I found out that IE does not insert the second javascript into the page unless the script has some text as well. For example if the page has a section like this:



Some stuff ...


And the returned code from ajax call has some text like this:

If we add the returned code to the page:


This would work in Firefox, but not IE and IE does not insert the code into the page at all, let alone executing it. But with some dummy text added to the returned block we can see the script in the page:
Return block from ajax call:


Some text


After this, I saw the script in the page, but still IE didn’t execute it. The simple solution was to write all client side scripts at the beginning when the page is being sent to the client. But in my situation, I needed to generate the second script on the fly with values entered by user in it. That means I couldn’t generate it at the beginning. Here is the solution I found for it.
To make it work with IE we need to insert the script inside the head section of the page. Not in the body.
JQuery has a function $('head',document) which give us the head section and this is the solution to IE’s problem of embedded scripts.
Let me show this to you with an example.

Here we have a simple html page:




And the somefile.php which is a server side script should return the new javascript block, without the <script> and </script> tags:


$output = ‘ $(function ( ) {
alert(“Hello!”);
});
‘;
echo $output;
?>

Remember that the url on the server that returns the javascript does not have script tag. This solved my problem. I hope it solves yours as well.