AJAX readyState is always 1

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dante671
    New Member
    • Feb 2010
    • 5

    AJAX readyState is always 1

    Hi

    I have been attempting to check that a username exists in a text file using JavaScript. I call the CheckUserExists () method (below) passing in the username. However the readyState is always 1 so the file does not get read.

    The webpage I am calling it from is something like this: www.mysite.co.u k/html/home.html

    and the text file is located at: www.mysite.co.u k/html/resources/somefile.txt

    I know really I should use server-side scripts but this is not possible so I need to use JavaScript.

    Anyone got any ideas where I am going wrong? This has been doing my head in all day so hopefully someone knows what I have done wrong.
    Code:
    var name;
    var file;
    	
    function CheckUserExists(username)
    {
    	name=username;
    	
    	if(window.XMLHttpRequest)
    	{
    		file = new XMLHttpRequest();
    	}
    	else if(window.ActiveXObject)
    	{
    		file = new ActiveXObject("Microsoft.XMLHTTP");
    	}
    	else
    	{
    		alert("Error XMLHTTP Not Supported");
    	}
    		
    	file.open("GET", "resources/somefile.txt", true);
    	file.onreadystagechange = ReadFile(); 
    	file.send(null);
    }
    
    function ReadFile()
    {
    	if(file.readyState == 4 || file.readyState == "complete") //Check file is ready to parse
    	{
    		if(file.status == 200) //Check file was found
    		{
    			//Read file etc...
    		}	
    	}
    	else
    	{
    		alert(file.readyState);
    	}
    }
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    Change line 22 to:
    Code:
    file.onreadystagechange = ReadFile;

    Comment

    • dante671
      New Member
      • Feb 2010
      • 5

      #3
      Thanks for the reply, I have made that change that you suggested and it now works.

      Very strange though as I tried it earlier and it didn't work but after going for dinner and coming back then making the change again it works.

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        Perhaps you were viewing a cached version of the page?

        Anyway, glad to hear that it's now working.

        Comment

        • dante671
          New Member
          • Feb 2010
          • 5

          #5
          It won't have been a cached version of the page as I tried clearing the cache a few times and then refreshing the page.

          Very pleased it's working it had been getting on my nerves. Thanks again for your help.

          Comment

          Working...