21

I am working on a web page that is using jQuery. I have an Ajax call that gets data from the server and updates a div. Inside that data there is a jQuery function, but the function is not being called after the data is loaded into the page. I have the proper js files included in the page already.

This is what is returned from the Ajax call and placed into a div:

<script type="text/javascript">
    $(function() {
         $('input').myFunction('param');             
    }); 
</script>
<p> other html </p>

How do I get the returned javascript to run after the html is inserted into the page?

(I am using Rails with the jRails plugin )

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
wusher
  • 12,291
  • 22
  • 72
  • 95

6 Answers6

27

If you want JavaScript tag evaluation, with html content, you should set the dataType option of the ajax call to "html":

$.ajax({
  type: "GET",
  url: "yourPage.htm",
  dataType: "html"
});

Or dataType "script", if you want to load and execute a .js file:

$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script"
});

more info here: Ajax/jQuery.ajax

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
7

I had a similar problem where I wanted to add little jquery date pickers to a couple fields I was retrieving via ajax. here is what I did to get around it... just quick and dirty. Instead of returning this whole block from my ajax call:

<script type="text/javascript">
    $(function() {
         $('input').myFunction('param');                         
    }); 
</script>
<p> other html </p>

I would return this (note the made up |x| separator)

    $(function() {
         $('input').myFunction('param');                         
    }); 

|x|

<p> other html </p>

Then when I received the data back via ajax, I split the return value into 2 parts: the javascript to be executed, and the html to display:

 r = returnvalfromajax.split("|x|");       
 document.getElementById('whatever').innerHTML = r[1];  
 eval(r[0]);
1

Changing

<script type="text/javascript">
...
</script>

To:

<script>
...
</script>

Fixed the issue for me.

JimFing
  • 151
  • 5
  • 11
-1

Well, you can use jQuery load() function: http://docs.jquery.com/Ajax/load#urldatacallback As a callback you can define function which will be executed after loading new content example:

$("#feeds").load("new_content.html",, doSomething());

and in new_content.html you can define function doSomething()...

-1

for ajax.net the endRequestHandler(sender, args) solution works fine though

dc2009
  • 842
  • 1
  • 9
  • 7
-7

have you tried Sys.WebForms.PageRequestManager.add_endRequest method?

    $(document).ready(function()
    {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);           
    }
    );
    function endRequestHandler(sender, args)
    {
        // whatever
    }
ajitatif
  • 117
  • 1
  • 9