Heshan Galahitiyawa
Heshan Galahitiyawa

Reputation: 13

How can I load jscript from ajax loaded html file?

I have an html file (index.html) with an empty div that loads its content from another html file (second.html) using ajax.

I'm using jqueryui to load a popup containing an audio player for a button click on the index.html.

When I have all the coding on the index.html like below, it works fine and displays the audio player on popup window on button click. - jsfiddle here

<html>
<head>
  <script type="text/javascript">
       $(function audioplay() {
    $( "#audio" ).dialog({
      autoOpen: false,
        modal: true,
        height: 100,
        width: 335,
      show: {
        effect: "blind",
        duration: 300
      },
      hide: {
        effect: "blind",
        duration: 300
      }
    });

    $( "#opener" ).click(function() {
      $( "#audio" ).dialog( "open" );
    });
  });
  </script>
</head>
<body>
<div id="stuff">
     <div id="audio" title="Places Are Connected">
         <audio controls autoplay>
           <source src="media/1.mp3" type="audio/mpeg">
           Your browser does not support this audio format.
         </audio>
     </div>
<button id="opener">Open Popup</button>
</div>
</body>
</html>

However, when I load the content in "stuff" from the second.html file, it doesn't work properly. Ex:

index.html

<body onload="loadXMLDoc()">
 <div id="stuff">
   <!--content from second.html loads here-->
 </div>
</body>

<script>
function loadXMLDoc(){
var xmlhttp;
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 && xmlhttp.status==200)
    {
    document.getElementById("stuff").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","second.html",true);
xmlhttp.send();
}

second.html

<div id="stuff">
 <div id="audio" title="Places Are Connected">
     <audio controls>
       <source src="http://www.hipstrumentals.com/wp-content/uploads/2014/02/Katy-Perry-Ft.-Juicy-J-Dark-Horse-Instrumental-Prod.-By-Dr.-Luke-Max-Martin-Cirkut.mp3" type="audio/mpeg">
       Your browser does not support this audio format.
     </audio>
 </div>
<button id="opener">Open Popup</button>
</div>

.JS file

$(function() {
$( "#audio" ).dialog({
  autoOpen: false,
    modal: true,
    height: 100,
    width: 335,
  show: {
    effect: "blind",
    duration: 300
  },
  hide: {
    effect: "blind",
    duration: 300
  }
});

$( "#opener" ).click(function() {
  $( "#audio" ).dialog( "open" );
});
});

When I use it like in the above example, the audio player just shows up on the index page itself. And the button appears below the player and does nothing.

I have tried so many methods to try and load JS with ajax but nothing worked so far. And since I'm new to both JS and ajax, I suspect there might be an easy fix that I'm missing. So any help to get it working properly would be much appreciated.

Upvotes: 0

Views: 912

Answers (2)

Michael
Michael

Reputation: 1467

I'm unclear what you mean with respect to loading JavaScript via AJAX, since the code you are trying to load doesn't contain any JS. However, as to why the audio player is not showing up as you expect it to, it looks as if the first part of your problem is that you don't have a div (or other element) with ID 'nonen' in index.html. You also don't need to repeat the definition of the 'stuff' div in second.html.

So I would remove the first and last lines of second.html, and change your onreadystatechange function to include

document.getElementById("stuff").innerHTML=xmlhttp.responseText;

Alternatively, since you're using jQuery already, I'd recommend using the built-in AJAX routines. Furthermore, depending on your desired effect I suspect you should be calling the jQuery UI dialog routine after you've added the second div (or after every time you load it, if it's changed again later).

For example, your current script could be replaced with something like the following (untested) code. First, you want to make sure that audioPlay() can be called at a later time, after your AJAX calls have finished, and also that it doesn't execute immediately on page load, before even the first one has completed.

audioPlay = function () { // Define a function to be called multiple times later
  $('#audio').dialog({
    ... // Fill in your options
  });
  $('#opener').click(function () {
    $('#audio').dialog('open');
  });
};

Next, you want the loadXMLDoc() function to call audioPlay() once the loaded HTML has been inserted into the DOM.

loadXMLDoc = function () {
  $('#audio').dialog('destroy'); // Get rid of any existing dialog
  $.ajax({
    dataType: 'html', // Load some HTML data via AJAX
    url: 'second.html', // From this file (relative URL)
    success: function (data) { // When the HTML has finished being downloaded...
      $('#stuff').innerHTML(data); // ...add it to the div with ID "stuff"
      audioPlay(); // ...and create a dialog for the new div
    }
  });
};

Upvotes: 1

Heshan Galahitiyawa
Heshan Galahitiyawa

Reputation: 13

Okay, got it fixed. Was a simple fix as I expected. Just had to make a runPopupJs() function and call it at onload.

function runPopupJs() {
 var head = document.getElementsByTagName('head')[0];
 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = 'js/popup.js';
 head.appendChild(script);
}

Called it by -

<body onload="loadXMLDoc();runPopupJs()">

Upvotes: 0

Related Questions