Executing JavaScript Code In AJAX Response


Read {count} times since 2020

This is the first post I am creating related to the Open project. This trick is used for posting posts and making that post appear at the first of the post feed. This tutorial will guide you on how to execute JavaScript code which is in the response of AJAX call. We are going to use **jQuery **for both AJAX handling.

This is the AJAX response :

<script>alert("Hello Subin");</script>

With a plain AJAX response, the code won’t execute. Even If you append the HTML code in AJAX response to the DOM, it won’t execute. To make it execute, you should use eval function. Some say eval is evil, but there is no other way for this purpose.

You should need a div wrapper that will store the AJAX responses :

<div id="ajax_responses" style="display:none;"></div>

The following code will execute an AJAX call and handle the AJAX response in a way to make the code in the AJAX response execute.

<script>
 $.post("ajaxResponse.php",{data : "some data"}, function(response){
   $("#ajax_responses").html(response);
   $("#ajax_responses").find("script").each(function(){
     eval($(this).text());
   });
 });
 </script>

What Happens ?

When the request is made, the server will return the JavaScript code inside script tag. jQuery will append the HTML response in #ajax_responses element. Then jQuery will loop through the script elements in the #ajax_responses element. Then the contents of the script tag is passed through eval function and the code will execute.

Show Comments