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 elementsjs
: 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.