Embedding HTML from jQuery AJAX Call Into Your Page

I got an interesting Twitter question the other day and thought I would blog about it to help anyone who has a similar situation.

Question

Hey buddy! How can I do a simple thing as loading a page into a div using Ajax and on the loaded page, execute a simple task as executing a javascript with an alert box?!? The page is loaded but the javascript just doesn't run! If I access the page direct directly, the alert pops out ok! --@montedesucata

ย 

Scenario 1

My initial thoughts were that he was trying to put an entire HTML document (pulled back from an AJAX call) inside another HTML document (the document that made the AJAX call). You can't do that because then youโ€™d have two html elements, two head elements, two body elements, etc... in one document. So, my first example was to put the contents into an iFrame.

Note: You can also, strip out the body content of the returned full HTML document and inject that into your current document, but then you might not have the correct scripts or css files that were included in the head element (or wherever you put those).

<!DOCTYPE html>


<meta charset=utf-8 />
Load Full HTML Document via AJAX into iFrame






Load Full HTML Document via AJAX into iFrame







The contents of the FullTestHtmlWithAlert.html are belowโ€ฆ


<!DOCTYPE html>


<meta charset=utf-8 />
Load Full HTML Document via AJAX into iFrame




Hello World From Full Html Document



The following is a screenshot of the results after clicking the Load button.

LoadFullHtmlDocumentViaAjaxIntoIframe

Feel free to Demo the above code below...

cooltext439924698

Scenario 2

The other scenario is that the HTML from the AJAX call is a partial document, meaning that it doesnโ€™t include html, head, body, etcโ€ฆ tags and is just content that might be found in a body tag. This is a simpler case and the results can easily be injected into another DOM element in the document.

<!DOCTYPE html>


<meta charset=utf-8 />
Load Full HTML Document via AJAX into iFrame





Load Parital HTML Document via AJAX into Div






The contents of the PartialTestHtmlWithAlert.html are belowโ€ฆ












1 2
a b

The following is a screenshot of the results after clicking the Load button.

LoadPartialHtmlDocumentViaAjaxIntoDiv

Feel free to Demo the above code below...

cooltext439924698

If you enjoyed this post, please consider sharing it with others via the following Twitter or Reddit buttons. Also, feel free to checkout my egghead.io profile page for addition free and subscription lessons, collections, and courses. As always, you can reach out to me on Twitter at @elijahmanor. Thanks and have a blessed day!

Reddit