Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a jQuery function inside html return from an AJAX call

Tags:

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 )

like image 580
wusher Avatar asked Oct 25 '08 05:10

wusher


People also ask

How do I return from AJAX?

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });

Can jQuery and AJAX be used together?

jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!

How get data from AJAX call in jQuery?

ajax({ type: "POST", url: 'test. php', data: {"type":"check"}, success: function(response){ alert(response); } }); There can obviously be more key-val pairs in data. In this case your alert should read: "The type you posted is check".


1 Answers

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

like image 65
Christian C. Salvadó Avatar answered Oct 19 '22 19:10

Christian C. Salvadó