Solved

ajax request stuck on readyState

Posted on 2013-05-21
5
750 Views
Last Modified: 2013-06-03
i am stuck in the readyState and can't figure out why, i was able to get my request locally, but when i threw it up on a local server the status is always 1. I am trying to do this without the help of jquery or other toolkits.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>history.pushState() Example - Joshua Rubin FEE Scripps Networks</title>
    
    <!--[if lt IE 9]>
    	<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script>
    <![endif]-->
    <style type="text/css">
		#loading {display:none;height:20px;width:20px;background:url('/~jrubin/pushstate/ajax-loader.gif') 0 0 no-repeat;}
	</style>

</head>

<body>

<div id="ajax">
	<div class="click" onclick="whereAmI()">
		Click One, I Dare You!
	</div>
	<ul id="menu" class="clearfix"> 
		<li><a href="/~jrubin/pushstate/seattle.html">Seattle</a></li>
		<li><a href="/~jrubin/pushstate/new-york.html">New York</a></li>
		<li><a href="/~jrubin/pushstate/london.html">London</a></li>
	</ul>
	<div id="location"></div>
	<div id="loading"></div>
</div>

<script type="text/javascript">

	//plain js version with click
	
		addEventListener("load",function(){
			var links= document.getElementsByTagName("a");
			for (var i=0;i<links.length;i++){
				links[i].addEventListener("click",function(e){
				console.log('this: ' + this);
				defineLocation(this);
				//prevent event action
				e.preventDefault();
				})
			}
		}); 		
	
	
	function defineLocation(thisGuy) {
			console.log('thisGuy: ' +thisGuy);

	/*
		console.log('thisGuy.href:');
		console.log(thisGuy.href);
		console.log('thisGuy.getAttribute(\'href\')"');
		console.log(thisGuy.getAttribute('href'));
		*/
		//pass url and execute
		whereAmI(thisGuy);
		
		
		// HISTORY.PUSHSTATE
		history.pushState('', 'New URL: '+thisGuy, thisGuy);
		//thisGuy.preventDefault();
		
	}
	
	/*
	// THIS IS WHERE THE MAGIC HAPPENS
	$(function() {
		$('a').click(function(e) {
			$("#loading").show();
			href = $(this).attr("href");
			console.log('lets load content');
			whereAmI(href);
			
			// HISTORY.PUSHSTATE
			history.pushState('', 'New URL: '+href, href);
			e.preventDefault();
			
			
		});
		
		// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
		window.onpopstate = function(event) {
			$("#loading").show();
			console.log("pathname: "+location.pathname);
			loadContent(location.pathname);
		};

	});
	*/

	function whereAmI(href){
		var url = href;
		var data = 'test'; 
		var method = 'GET';
		var async = true;
		var req = false;
		console.log('make request: ')
		// Mozilla/Safari/Non-IE
		if (window.XMLHttpRequest)
		{
			req = new XMLHttpRequest();
			console.log('new request');
		}
		// IE
		else if (window.ActiveXObject)
		{
			req = new ActiveXObject("Microsoft.XMLHTTP");
		}

		// If AJAX supported
		if(req != false)
		{
			console.log('we got here');
			// Open Http Request connection
			console.log('method :' + method);
			console.log('url :' + url);
			console.log('async :' + async);
			req.open(method, url, async);
			// Set request header (optional if GET method is used)
			//req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			// Callback when ReadyState is changed.
			req.onload = function()
			{
				console.log('req.readyState: '+ req.readyState)
				if (req.readyState == 4)
				{
					var txt = req.responseText;
					console.log('txt: ' +txt);
					var tmpBox = document.createElement( 'div' );
					
					//set html of request inside hidden box
					tmpBox.innerHTML = txt;
					console.log('tmpBox.innerHTM: ' +tmpBox.innerHTML);

					//var getBox = document.getElementById('wrapper');
					//var relTxt = getBox.innerHTML;
					//console.log(relTxt);
					var status = document.getElementById("location");
					
					status.innerHTML = tmpBox.innerHTML;
					
					var getBox = document.getElementById('wrapper');
					
					if(getBox.innerHTML != null) { var relTxt = getBox.innnerHTML} else {var relTxt = 'fail';}
					var relTxt = getBox.innerHTML;
					
					status.innerHTML = relTxt;
					
					//$("#loading").hide();

					//console.log(req.responseText);
				}
			}
			//req.send(data);
		}
		else
		{
			alert("Please use browser with Ajax support.!");
		}
		
	}

</script>


</body>
</html>

Open in new window

0
Comment
Question by:JMRFan4Life
  • 3
  • 2
5 Comments
 
LVL 82

Assisted Solution

by:hielo
hielo earned 400 total points
ID: 39186283
>>req.onload = function(){...}
should be req.onreadystatechange = function(){...}
0
 

Author Comment

by:JMRFan4Life
ID: 39191083
That was actually like that before, i tried that as an alternative,

here is a live url for my example:

http://officewebpool.com/test/pushstate/history.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>history.pushState() Example - Joshua Rubin FEE Scripps Networks</title>
    
    <!--[if lt IE 9]>
    	<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script>
    <![endif]-->
    <style type="text/css">
		#loading {display:none;height:20px;width:20px;background:url('/test/pushstate/ajax-loader.gif') 0 0 no-repeat;}
	</style>

</head>

<body>

<div id="ajax">
	<div class="click" onclick="whereAmI()">
		Click One, I Dare You!
	</div>
	<ul id="menu" class="clearfix"> 
		<li><a href="/test/pushstate/seattle.html">Seattle</a></li>
		<li><a href="/test/pushstate/new-york.html">New York</a></li>
		<li><a href="/test/pushstate/london.html">London</a></li>
	</ul>
	<div id="location"></div>
	<div id="loading"></div>
</div>

<script type="text/javascript">

	//plain js version with click
	
		addEventListener("load",function(){
			var links= document.getElementsByTagName("a");
			for (var i=0;i<links.length;i++){
				links[i].addEventListener("click",function(e){

				defineLocation(this);
				//prevent event action
				e.preventDefault();
				})
			}
		}); 		
	
	
	function defineLocation(thisGuy) {
		//pass url and execute
		whereAmI(thisGuy);
		
		// HISTORY.PUSHSTATE
		history.pushState('', 'New URL: '+thisGuy, thisGuy);
	}
	
	function whereAmI(href){
		var url = href;
		var data = 'test'; 
		var method = 'GET';
		var async = true;
		var req = false;
		// Mozilla/Safari/Non-IE
		if (window.XMLHttpRequest)
		{
			req = new XMLHttpRequest();
		}
		// IE
		else if (window.ActiveXObject)
		{
			req = new ActiveXObject("Microsoft.XMLHTTP");
		}

		// If AJAX supported
		if(req != false)
		{
			console.log('we got here');
			// Open Http Request connection
			req.open(method, url, async);
			
			//test ready state
			console.log('req.readyState: '+ req.readyState)

			// Callback when ReadyState is changed.
			req.onreadystatechange  = function()
			{
				console.log('req.readyState: '+ req.readyState)
				if (req.readyState == 4)
				{
					var txt = req.responseText,
						tmpBox = document.createElement( 'div' ),
						status = document.getElementById("location");

					console.log('txt: ' +txt);
					
					//set html of request inside hidden box
					tmpBox.innerHTML = txt;

					
					status.innerHTML = tmpBox.innerHTML;
					//set variable after wrapper element is inserted into the dom
					var getBox = document.getElementById('wrapper');
					
					if(getBox.innerHTML != null) { var relTxt = getBox.innnerHTML} else {var relTxt = 'fail';}
					var relTxt = getBox.innerHTML;
					
					status.innerHTML = relTxt;
					
				}
			}
		}
		else
		{
			alert("Please use browser with Ajax support.!");
		}
		
	}

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

Open in new window

0
 
LVL 82

Accepted Solution

by:
hielo earned 400 total points
ID: 39192002
On line 42:
>>defineLocation(this);

"this" is not the url of the <a> tag.  Instead it IS the <a> tag.  Thus on line 59:
>>var url = href;
url is a reference to the clicked <a> tag, not its url.  Try passing:

defineLocation(this.href);

Open in new window


Also use the following:
				//prevent event action
				if(typeof(e.preventDefault)!="undefined")
					e.preventDefault();
				else
					e.returnValue=false;

Open in new window

NOTE: e.returnValue=false; is meant for IE browsers
Lastly, there is no need for:
var links= document.getElementsByTagName("a");

Open in new window


The browser already provides you with document.links which is an "array" of all the links in the current document:
var links= document.links;

Open in new window

0
 

Assisted Solution

by:JMRFan4Life
JMRFan4Life earned 0 total points
ID: 39205688
I figured out the actual error with the request:

req.send(''); was removed accidentally at some point and the request was never being sent.
0
 

Author Closing Comment

by:JMRFan4Life
ID: 39215647
some helpful tips in here, my comment was selected since the reason the ajax request was stuck in state 1 was because the request was never actually being sent.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes how to create custom column layout styles for Bootstrap. The article uses 5 columns to illustrate the concept, but the principle can be extended to any number of columns.
Finding original email is quite difficult due to their duplicates. From this article, you will come to know why multiple duplicates of same emails appear and how to delete duplicate emails from Outlook securely and instantly while vital emails remai…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now