Search code examples
javascripthtmlajaxtextchanged

What is wrong with my simple AJAX example. Does you website have to be on a server?


I'm not sure what is wrong all my files are in the same folder. First I will post HTML, then AJAX, and finally the .txt file.

HTML:

<!doctype html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Title of webpage</title>
    <link rel="stylesheet" type="text/css" href="main.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="javascript.js"></script>
</head>
<body>
    <div id="myDiv"><h2>Let AJAX change this text</h2></div>
    <button onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

And my javascript/AJAX:

function loadXMLDoc(){
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("GET", "test.txt", true);
xmlhttp.send();
}

And my .txt file:

<h3>This text was changed</h3>
<p>And also I added a random paragraph</p>

Thankyou in advance for the help.


Solution

  • What you have looks quite good for your first steps with AJAX. But you really need a webserver. To get your example work, do the following:

    1. Install a webserver on your machine. I suggest you use XAMPP for your first steps. Get it from here: http://www.apachefriends.org/en/xampp.html You should not have to configure something by yourself, just install it and you should end up with a webserver which runs "out-of-the-box".
    2. Place all your files in the htdocs folder. In my example I named the HTML file ajax.html.
    3. Ensure that your webserver is running. Open a browser and navigate to localhost. You should see a page with a big XAMPP on it.
    4. Navigate to localhost/ajax.html. I tested your code and it worked.

    Maybe this W3CSchools AJAX tutorial can provide you with more information about AJAX.