0

I am trying to dynamically load html content and execute JS on ajax response. The response object has two key:value pairs.

  • content: having the html elements
  • js: having the required js

Here's the code:

$.post("/some_url.php",{job: "getThatPage"},function(response) {

    /* parsing response as JSON */
    let ajaxResponse = JSON.parse(response);

    /* adding content to page body */
    $("body").html(ajaxResponse.content);

    /* now ajax.js is a string containing the required JS*/
    /* how to execute this script? */

});

Script returned from an ajax request doesn't get executed even If its added to the DOM, thats why I have separated the content and script. I know I can put the required JS into a separate file and load it with getScript() on success but that wont help me here because my ajax request is returning some customised JS for every logged in user.

I think it can be solved if somehow I was able to create a .js file and put the contents of ajax.js into it and load it using getScript() method. That's what my silly mind tells me.

Help would be appreciated.

saibbyweb
  • 2,864
  • 2
  • 27
  • 48
  • Duplicate of [this SO question](https://stackoverflow.com/questions/14521108/dynamically-load-js-inside-js) Surely you saw it by now :). – Itamar Jun 24 '18 at 13:21

1 Answers1

1

Are you sure the content contains a script tag? If not wrap it in one.

$('body').append ($('<script>').html(ajaxResponse.content));
kagronick
  • 2,552
  • 1
  • 24
  • 29
  • Content doesn't contain any script tags. thanks a ton, learned something new today. BTW its `ajaxResponse.js` instead of `ajaxResponse.content`. – saibbyweb Jun 24 '18 at 13:34