Sample Ajax request

JMRFan4Life
JMRFan4Life used Ask the Experts™
on
hey all,

i am trying to write a plain javascript example that makes a simple ajax request and i cannot get it to work. Not sure what I am missing, the Jquery method works.

I have created a folder with this code below in an html file and a plain text file called test.txt

Thanks
<!DOCTYPE html>  
<html>  
<head>
<title>Ajax test</title> 
 
</head>  
<body>

<div id="container">fail blog</div>
<script type="text/javascript">

		var xhr;
		
		xhr = new XMLHttpRequest();

		xhr.onreadystatechange = ensureReadiness;

		function ensureReadiness() {
			if(xhr.readyState < 4) {
				return;
			}

			if(xhr.status !== 200) {
				return;
			}

			// all is well
			alert('wtf');
			console.log(xhr.responseText);
			
		}

		xhr.open('GET', 'test.txt', true);
		xhr.send('');
		
		//jquery method
		//$('#container').load('test.txt');
</script>
</body>
</html>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
after some adjustments and cleanup i have this. i can log the ready state and state 3 displays the resposneText, however i never hit 4.

<!DOCTYPE html>  
<html>  
<head>
<title>Ajax test</title> 
 
</head>  
<body>

<div id="container">fail blog</div>
<script type="text/javascript">


var ajaxLoadTest = {

	LoadTextFile : function(url, callback){
		var xhr;
		
		xhr = new XMLHttpRequest();

		xhr.onreadystatechange = ensureReadiness;

		function ensureReadiness() {
			if(xhr.readyState < 4) {
				console.log(xhr.responseText + 'readyState =' + xhr.readyState );
				
				return;
			}

			if(xhr.status === 200) {
				console.log('great failure' + xhr.responseText);
				return;
			}
			
			if(xhr.status === 4) {
				console.log('great success' + xhr.responseText);
				callback(xhr);
			}
			
		}

		xhr.open('GET', url, true);
		xhr.send('');
		
		//jquery method
		//$('#container').load('test.txt');

	}
};


ajaxLoadTest.LoadTextFile('test.txt', function(xhr){console.log(xhr.responseText)});

</script>
</body>
</html>

Open in new window

I don't know what you are seeking to achieve accessing a .txt file through an AJAX call.

First thing I'd check on a problem of this type is that my url is being fully understood by the browser. Keep in mind that test.txt is not exactly a url, and if your browser correctly states that it's a file it will seek that file on a path that probably is not the place where your .html file is.

Try using a url with full path to the file.
Top Expert 2007

Commented:
It never reaches 4 because:
if(xhr.readyState < 4) {

Open in new window

says if it is LESS THAN 4.
Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Author

Commented:
I figured out my issue,
I was testing if status was 4 instead of readystate.

This is just an Ajax example to learn the native Javascript Ajax process which will then provide a better foundation for using other Javascript libraries.
Top Expert 2007

Commented:
>>I figured out my issue,

Odd, because I thought I pointed out the problem?
Commented:
Try mod below:
<!DOCTYPE html>  
<html>  
<head>
<title>Ajax test</title> 
 
</head>  
<body>

<div id="container">fail blog</div>
<script type="text/javascript">

		var xhr;
		
		// creates XMLHttpRequest object
                if (window.XMLHttpRequest) {
                    xhr = new XMLHttpRequest();
                }
                else if (window.ActiveXObject) {
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                }
		xhr.open('GET', 'test.txt', true);
                xhr.send(null); 

                // gives the request object an event handler
                xhr.onreadystatechange = function() {
                    if ((xhr.readyState == 4) && (xhr.status == 200)) {

			// all is well
			alert('wtf');
			console.log(xhr.responseText);
                    }
		}

		//jquery method
		//$('#container').load('test.txt');
</script>
</body>
</html>

Open in new window

Author

Commented:
I never said your were incorrect, but I had an issue with my test condition that was further down in the code. Originally I was logging the readyState to test progression. I left that our is the posted code. Both ways solve the issue.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial