0

Below is a snippet of code I have for an Ajax request. The request works, but when the request is processed the page appears without any of the CSS (even though I have everything in the same directory). To test this I made the request point to a page on my site that already existed. Any help? Thanks in advance.

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","ajaxtest.html",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
5
  • Is ajaxtest.html loading any CSS files? Commented Feb 11, 2011 at 21:01
  • Can you add more of the code. Such as what you have in the myDiv? Also, what are you passing back? Commented Feb 11, 2011 at 21:02
  • Yes, I pointed the request to a page that already exists on my page and when not viewed through the Ajax request all the CSS is there. Commented Feb 11, 2011 at 21:03
  • @JAmie - the code is there now - he hadn't formatted it in a way that would permit the HTML tags to be shown. Commented Feb 11, 2011 at 21:04
  • wow..that was really strange. for some reason it started working. i don't know what the deal was. oh well, thanks for the consideration! Commented Feb 11, 2011 at 21:05

4 Answers 4

1

Injecting css in a page via Ajax is not supported by all browsers (whether inline or via a <link> tag).

The solution is to load the CSS for the ajax content in the page containing the Ajax call.

Sign up to request clarification or add additional context in comments.

Comments

0

According to W3 Schools, a <link> element for a stylesheet can only appear in your document <head>.

Hence if you include the contents of a whole external file (that links its own styles) within your <div> those won't be loaded.

Comments

0

The problem is that you are overwriting the H2 tag with the innerHTML. if you had something like

<h2 id="myDiv">Let AJAX change this text</h2>

It would keep the h2. Or you need to have the AJAX pass back:

<h2>What I want to change it to</h2>

Comments

0

Move your css inside a <style> element inside the pege you request with ajax. Should do the trick.

Second way is to insert the css for the page you request with ajax into the css file of the page from witch you request.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.