422
422

Reputation: 5770

loading content with jQuery / Ajax

I am working on a small code snippet.

The Issue: I want to have a couple of buttons, that on click load content into a div, using ajax.

I can get it working absolutely fine, with say images, and text. But cannot load with css and js.

Example: the index page:

<input type="button" onclick="example_ajax_request()" value="Click Me!" /> | <input type="button" onclick="example_ajax_request2()" value="Or Me!" />
<div id="example-placeholder">
   <p>Placeholding text</p>
</div>

<script type="text/javascript">
function example_ajax_request() {
  $('#example-placeholder').html('<p><img src="images/loader.gif" width="220" height="19" /></p>');
  $('#example-placeholder').load("fat.html");
}
</script>
<script type="text/javascript">
function example_ajax_request2() {
  $('#example-placeholder').html('<p><img src="images/loader.gif" width="220" height="19" /></p>');
  $('#example-placeholder').load("joined_today.html");
}
  </script>

The page joined_today.html is a full blown webpage ( which contains a div element ) only, and shaows AMCHARTS. Which obviously utilise js inc Raphael.

Anyhoo, the issue arises, from any webpage with headers, html and body tags. The script above doesnt render these.

So what am i doing wrong. Seemingly, we can only load into div id example_placeholder content that doesnt include JS, or CSS

Is there a better way.

Essentially our scenario is this ( I want to avoide iFrames )

We have web page, and a content div, with 3 buttons above the div. On click of each button, the div gets loaded with a chart ( using amcharts js version ) On click of another button , another chart gets loaded inplace of the first chart, etc etc

Perhaps I am going about this wrong, any help appreciated.

Ste

Upvotes: 0

Views: 845

Answers (2)

iivel
iivel

Reputation: 2576

Easy way to do this: load the js and CSS files on the parent page.

Upvotes: 0

William Niu
William Niu

Reputation: 15853

You need to insert the <style>, <link> and <script> tags in another place, e.g. <head> or end of <body> with something like:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'somescript.js';
document.getElementsByTagName('head')[0].appendChild(script);  

One potential problem is to check whether a file (css or javascript) has been inserted. You may need to maintain a global list to check whether a file is already included.

Take a look at this source for "DOM-based On-Demand JavaScript".

Upvotes: 1

Related Questions