Executing javascript function returned from AJAX response (PHP)

I am trying to load a javascript function as soon as Ajax returns the HTML code via PHP. This requires me to echo javascript in the ajax response.

In other words, I am trying to add this code (placed between script tags) to PHP Ajax response .. hoping it will execute

  $ ('# green'). smartpaginator ({Some code ...}); 

From what I have read so far, the browser has made reading Javascript and will not execute it. Is there any way to do this ....?

+7
source share
1 answer

You should evaluate this code like this

eval("("+response+")"); 

OR

If your answer contains both html and javascript code, you should do it like this

  $.ajax({ url: "/snippets/js-in-ajax-response.html", context: document.body, success: function(responseText) { $("#response-div").html(responseText); $("#response-div").find("script").each(function(i) { eval($(this).text()); }); } }); 
+19
source

All Articles