title: Executing javascript script after ajax-loaded a page - doesn't work
body: <p>I'm trying to get a page with AJAX, but when I get that page and it includes Javascript code - it doesn't execute it.</p>
  
  <p>Why?</p>
  
  <p>Simple code in my ajax page:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  alert("Hello");
  &lt;/script&gt;
  </code></pre>
  
  <p>...and it doesn't execute it. I'm trying to use Google Maps API and add markers with AJAX, so whenever I add one I execute a AJAX page that gets the new marker, stores it in a database and should add the marker "dynamically" to the map.</p>
  
  <p>But since I can't execute a single javascript function this way, what do I do?</p>
  
  <p>Is my functions that I've defined on the page beforehand protected or private?</p>
  
  <p>** UPDATED WITH AJAX FUNCTION **</p>
  
  <pre><code>function ajaxExecute(id, link, query)
  {
      if (query != null)
      {
          query = query.replace("amp;", "");
      }
  
      if (window.XMLHttpRequest)
      {
          // code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
      }
      else
      {
          // code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
  
      xmlhttp.onreadystatechange=function()
      {
          if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200)
          {
              if (id != null)
              {
                      document.getElementById(id).innerHTML=xmlhttp.responseText;
              }
          }
      }
  
      if (query == null)
      {
          xmlhttp.open("GET",link,true);
      }
      else
      {
          if (query.substr(0, 1) != "?")
          {
              xmlhttp.open("GET",link+"?"+query,true);
          }
          else
          {
              xmlhttp.open("GET",link+query,true);
          }
      }
      xmlhttp.send();
  }
  </code></pre>
  
  <p>** Solution by Deukalion **</p>
  
  <pre><code>var content = xmlhttp.responseText;
  
  if (id != null)
  {
  
      document.getElementById(id).innerHTML=content;
      var script = content.match("&lt;script[^&gt;]*&gt;[^&lt;]*&lt;/script&gt;");
  
      if (script != null)
      {
          script = script.toString().replace('&lt;script type="text/javascript"&gt;', '');
          script = script.replace('&lt;/script&gt;', '');
          eval(script);
  
      }
  }
  </code></pre>
  
  <p>and on certain events, I had to within the script addevent listeners instead of just making a "select onchange='executeFunctionNotIncludedInAjaxFile();'" I had to addEventListener("change", functionName, false) for this. In the script that is being evaluated.</p>