JereTheJuggler
JereTheJuggler

Reputation: 137

Fetch an html element from external page with javascript

I'm trying to create a function in javascript the will create a video html element, and get the source by retrieving a source element from another web page

I've seen other questions with answers using jquery or some ajax stuff, but nobody actually explains themselves, so all I can do is copy and paste whatever they say into my page and get an error saying "$" is undefined (I'm rather new to javascript if you couldn't tell. Haven't used any ajax or jquery yet).

function loadSource(url){
    var vid = document.getElementById("vid");
    var src = <get source element with id "mp4Source" from the specified url>
    vid.appendChild(src);
}

Upvotes: 3

Views: 13998

Answers (1)

Toby Mellor
Toby Mellor

Reputation: 8205

The reason why you're getting $ as undefined is because you have not added the JQuery Library.

There is a good question explaining how to get setup here

Above your JavaScript, you need to include the JQuery Library.

Example of how to include the JQuery Library

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

As for loading the external video element, you need to make an AJAX request to the URL containing the element. AJAX is a way to perform Asynchronous HTTP requests, e.g. requests that are made to a URL without refreshing the web page.

Example of how AJAX can be used to pull HTML from an external URL

function loadSource(url){
    $.ajax({
        url: "<URL containing the HTML>",
    })
    .done(function(html) {
        $("#vid").append(html); // append the html to the element with the ID 'vid'
    });
}

More information on AJAX can be found at http://api.jquery.com/jquery.ajax/

You should also look into the basics of JQuery, such as looking here. An example of how this could be used in your code is by replacing document.getElementById("vid") with $("#vid").

Upvotes: 4

Related Questions