user1149557
user1149557

Reputation: 15

Load javascript files with ajax

Just a simple question. (probably really basic I quess)

Using XmlHttp I am able to load a page, but not sure how to iclude the js files..

How can I alter the code in the images below, to be able to include the two java script files into the page loaded with ajax? I'm by far not a java script programmer, so really needs some help.

Thank you.

clientside.php:

<html>
<head>
<title></title>
  <script src="XmlHttp.js"></script>
  <script>
    var urlServer ="serverside.php";
    var xmlObj = null;

    function callServer(urlServer){
      xmlObj= XmlHttp.create();
          if(xmlObj) {
            xmlObj.onreadystatechange = responseFromServer;
            xmlObj.open("GET", urlServer, true);
            xmlObj.send();
          }
    }       

    function responseFromServer() {
      if (xmlObj.readyState == 4) {
        if (xmlObj.status == 200) {
          document.getElementById("main").innerHTML = xmlObj.responseXML.getElementsByTagName("mybody")[0].firstChild.nodeValue;
          eval(xmlObj.responseXML.getElementsByTagName("myscript")[0].firstChild.nodeValue);                
        }
      }
    }   
  </script>
</head>
<body>
  <div id="main"></div>
  <input type="button" value="Begin test" onClick="callServer(urlServer)">
</body>
</html>



serverside.php :

<?php
  //How do I load these two javascript files together with the <body> below.
  //Obviously the method below does not work..
  $script="
   <script type='text/javascript' src='SlimBox/js/mootools.js'></script>
   <script type='text/javascript' src='SlimBox/js/slimbox.js'></script>
  ";

  $body="
    <body>
    <a href='img/facebook-icon.png' rel='lightbox[roadtrip]' cap='test'><img alt=''border='0' src='img/facebook-icon.png' /></a>
    </body>
  ";

  //Now build the xml page:
  $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
  $xml .= "<mypage>";
  $xml .= "<myscript>".htmlentities($script)."</myscript>";
  $xml .= "<mybody>".htmlentities($body)."</mybody>";
  $xml .= "</mypage>";
  header('Content-type: text/xml');
  echo $xml;
?>

Upvotes: 0

Views: 8308

Answers (1)

Emmanuel N
Emmanuel N

Reputation: 7449

most efficient way will be to use ajax to load script source(uri) and use javavcript to update script source

Something like:

 document.getElementById('external_script').src = 'http://cross.domain.com/other.js';

Fore more on how to load script dynamically check

Upvotes: 1

Related Questions