-2

I have different websites that have the same data protection. So that the text does not have to be changed every time on all pages, there is a file on another server that is integrated via Ajax.

There is a part where you can set an opt-out and the domain of the respective page must be stored there.

<a href="#" id="setOptOut">I don't want to get tracked!</a>
<script type="text/javascript">
  document.getElementById("setOptOut").addEventListener('click', function(e) {
    e.preventDefault();
    var redirect = 'https://' + window.location.hostname + '/privacy';
    var url = encodeURIComponent(redirect);
    location.href = url;
  });
</script>

The code above which is in an HTML file is loaded successfull via Ajax into the document of the web page, but when I click on the link the function is not executed.

If I call the HTML file directly on the server, everything works as expected. Why doesn't it work with Ajax?

  • 1
    _“Why doesn't it work with Ajax?”_ - what AJAX, you have not shown any. – CBroe Aug 10 '20 at 11:53
  • And you probably haven’t done much research before asking either, I am guessing? https://stackoverflow.com/questions/2592092/executing-script-elements-inserted-with-innerhtml – CBroe Aug 10 '20 at 11:54
  • [Google: "javascript not executed when inserted via ajax site:stackoverflow.com"](https://www.google.com/search?q=javascript+not+executed+when+inserted+via+ajax+site:stackoverflow.com) – CBroe Aug 10 '20 at 11:54
  • I read all the threads but for me it seems not the same problem. Maybe I don't just understand it. I just load an HTML file with text and the javascript block above. – TurtleOnTheBack Aug 10 '20 at 12:17
  • @TurtleOnTheBack Please [edit] your question with the code that you use to insert this into your webpage. – Ivar Aug 10 '20 at 12:18
  • The use of encodeURIComponent does not make sense here – epascarello Aug 10 '20 at 13:33

1 Answers1

0

Found this good example: https://subinsb.com/how-to-execute-javascript-in-ajax-response/

I used eval() to make the code in the AJAX response execute.