0

My source from W3 Schools : https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax_array

When I running this ajax example in w3 source it's running successfully.

When I try to execute the same code in my local its' not running. The code is below.

Is there I need any server for running this example?

ajax.html

<!DOCTYPE html>
<html>
<body>

<h2>Use the XMLHttpRequest to get the content of a file.</h2>

<p id="demo"></p>

<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var myObj = JSON.parse(this.responseText);
    document.getElementById("demo").innerHTML = myObj.name;
  }
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
</script>

</body>
</html>

json_demo.txt

{
    "name":"John",
    "age":31,
    "pets":[
        { "animal":"dog", "name":"Fido" },
        { "animal":"cat", "name":"Felix" },
        { "animal":"hamster", "name":"Lightning" }
    ]
}

How to run this file in my local computer? Help me to begin my Ajax Learning......

7
  • 1
    You cannot read the local file from javascript. It is against the security protocol. Commented Dec 31, 2019 at 10:20
  • Yes, you would need a localhost server, e.g. XAMPP Commented Dec 31, 2019 at 10:23
  • Then how to run this ? Commented Dec 31, 2019 at 10:23
  • @AkashShrivastava suggest any sites for xampp with ajax. Commented Dec 31, 2019 at 10:25
  • 1
    I would suggest instead of using your own file, use a public API to get data (e.g. public dummy rest api) here you'll find plenty endpoints from where you can fetch json. Just replace "json_demo.txt" in xmlhttp.open("GET", "json_demo.txt", true); with any of those public URLs Commented Dec 31, 2019 at 10:28

1 Answer 1

1

In order to run this example on local machine you should use Web server. You can setup any web-server you want to serve static txt file you mentioned.

Here some of them:

Because you're studying JS I'd suggest you to use Node.js and create a simple HTTP server. Look at the answers for this question if you're interested in this way: Node.js quick file server (static files over HTTP)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.