Solved

ajax request stuck on readyState

Posted on 2013-05-21
5
756 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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Suggested Solutions

Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
In this tutorial viewers will learn how to position overlapping items using z-index in CSS. They will also learn the restrictions on the z-index property.  Create a new HTML document with an internal stylesheet.: Create a div in CSS and name it Red.…
In this tutorial viewers will learn how to style elements, such a divs, with a "drop shadow" effect using the CSS box-shadow property Start with a normal styled element, such as a div.: In the element's style, type the box shadow property: "box-shad…

785 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