Link to home
Start Free TrialLog in
Avatar of roy_sanu
roy_sanuFlag for India

asked on

Ajax question

Hi,
 
I have a question when i was  trying to run the index.html on the  browser like firefox and chrome it is not displaying the data as  Hello world. Let me what is the problem

Thanks
data.txt
script.js
index.html
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
jQuery is just javascript packaged up in easier to use functions as @JulianH has shown.  But what I like most about it is it's cross browser compatible.  It takes care of all the nuances between browser specific objects such as XMLHttpRequest or ActiveXObject("Microsoft.XMLHTTP") and allows you to do all this with a few lines.

Back to your question, what I also think is missing is your code is running potentially before the page has finished rendering but that's also where jQuery comes in handy with the $(function() { ... } that JulianH has wrapped around the ajax code.  It will wait until the page has loaded before running.
Avatar of roy_sanu

ASKER

i understand that on juery one can run, but  with ajax why it is not working on my system, it working on my friends machine
Are you running it on a server http://www.mywebsite.com/index.html or locally eg file://path/to/your/index.html

Do you see any error messages in the developer tools (press f12 and click on the console tab in Chrome)
I am running locally...

My code is like this

in the data.txt i have Hello world

In the script.js file i have
-----------------------------------------------------------------------------------------
var request;
if (window.XMLHttpRequest) {
      request = new XMLHttpRequest();
} else {
      request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET', 'data.txt');
request.onreadystatechange = function() {
      if ((request.readyState===4) && (request.status===200)) {
            console.log(request);
            document.writeln(request.responseText);
      }
}
request.send();
-------------------------------------------------------------------------------------------------

In the  index.html i have
=============================================
<!DOCTYPE html>
<html lang="en">
<head>
      <meta charset="utf-8" />
      <title>JavaScript AJAX</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
============================================================

where is the problem i donot know..

I keep all the files at the same place or same folder

It is not showing any error nor it is printing as javaScript AJAX with Hello World.

it is blank.
i thought so.  it's not going to work.  You'll need a server to get it to work, which can be localhost if you have iis installed

this is what i get:

User generated image