I got a backend API written in PHP (w/ Laravel) which has one specific controller that receives an ID, makes a few DB actions to retrieve some data and then populates a dynamic js code (simply attaching it as a string to a variable, and returns it) based on the DB results and returns this code as a string.
On the client side though, what I'm willing to achieve is that on each entrance to the website, an ajax call will be sent to this API endpoint and a dynamic js piece of code will be attached to the DOM (and will be executed as well, of course).
For now, the API works well and returns the exact code that I'm willing, and on the client side I'm able to fetch it via a simple xhr request and attach it to the DOM, but the only problem is that it doesn't execute.
Current JS code for the API call:
<script>
const url = 'http://127.0.0.1:8000/api/campaigns/1/1'; // get campaign
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState === 4 && xhr.status === 200) {
let response = xhr.responseText;
let div = document.getElementById('campaigns');
div.insertAdjacentHTML( 'beforeend', response );
}
}
</script>
And the response is a string that contains a whole new script to be attached (and executed).