Jump to content

Data from File


lilman

Recommended Posts

I am new to Ajax and JavaScript so I am hoping someone who knows a little about these languages can help me. In my book there is this example, but it doesn't work. It script has a button so when someone clicks on it, it retrieves data from a file and prints the string. The data.txt file is in the same folder, so I know that it is not that.  However with my little knowledge of Ajax I see nothing wrong with this code.

[code]<html>
  <head>
    <title>Ajax at work</title>

    <script language = "javascript">
      var XMLHttpRequestObject = false;

      if (window.XMLHttpRequest) {
        XMLHttpRequestObject = new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
      }

      function getData(dataSource, divID)
      {
        if(XMLHttpRequestObject) {
          var obj = document.getElementById(divID);
          XMLHttpRequestObject.open("GET", dataSource);

          XMLHttpRequestObject.onreadystatechange = function()
          {
            if (XMLHttpRequestObject.readyState == 4 &&
              XMLHttpRequestObject.status == 200) {
                obj.innerHTML = XMLHttpRequestObject.responseText;
            }
          }

          XMLHttpRequestObject.send(null);
        }
      }
    </script>
  </head>

  <body>

    <H1>Fetching data with Ajax</H1>

    <form>
      <input type = "button" value = "Display Message" onClick = "getData('data.txt', 'targetDiv')">
    </form>

    <div id="targetDiv">
      <p>The fetched data will go here.</p>
    </div>

  </body>
</html>
[/code]

Thanks in advance!
Link to comment
Share on other sites

Well, normally the way this works is that your processing occurs in a backend php file... I have never seen anyone just pull directly from a text file like that in the JS, since the text file obviously resides on the server.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.