Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jul 2012
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    onreadystatechange disfunction

    Hello,
    I have a problem with a command in javascript, during an AJaX call.
    I use the following code to detect when the readyState of a variable has changed so that I call another function.

    Code:
    myrequest.onreadystatechange=getData();
    
    function getData() {
    
    if (myrequest.readyState===4) {
    if  (myrequest.status===200) {
    var text=myrequest.responseText;
    alert(text);
    
    }
    
    }
    
    }
    The problem is that the command onreadystatechange does not work properly because the function getData() gets loaded before the readyState of myrequest has changed. What can I do to fix this?

  • #2
    Regular Coder
    Join Date
    Aug 2010
    Posts
    967
    Thanks
    19
    Thanked 211 Times in 209 Posts
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Test</title>
    </head>
    <body>
    Procedure started
    <script type="text/javascript">
    var myrequest=new XMLHttpRequest;
    myrequest.open("GET",'test.txt',true);
    myrequest.onreadystatechange=getData;
    function getData() {
    	if (myrequest.readyState===4) {
    		if (myrequest.status===200) {
    			var text=myrequest.responseText;
    			alert(text);
    		}
    	}
    }
    myrequest.send(null);
    
    </script>
    </body>
    </html>

  • Users who have thanked DaveyErwin for this post:

    A-man (08-02-2012)

  • #3
    New Coder
    Join Date
    Jul 2012
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thank you very much DaveyErwin,
    It worked thank you again.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •