Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a javascript function returned from AJAX response (PHP)

Tags:

jquery

ajax

php

I am trying to load a javascript function once Ajax has returned the HTML code through PHP. This requires me to echo the javascript in the ajax response.

In other words i am trying to add this code (placed between script tags) in the PHP Ajax response.. hoping that it executes

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

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

like image 261
rohan Avatar asked Jul 27 '12 03:07

rohan


1 Answers

You have to Evaluate that code like this

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

OR

If your response contains both html and javascript code you have to do 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());
                });
            }
        });
like image 193
Bhavik Patel Avatar answered Oct 13 '22 23:10

Bhavik Patel