?
Solved

ajax request stuck on readyState

Posted on 2013-05-21
5
Medium Priority
?
838 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 1200 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 1200 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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

When it comes to write a Context Sensitive Help (an online help that is obtained from a specific point in state of software to provide help with that state) ,  first we need to make the file that contains all topics, which are given exclusive IDs. …
The first step to building an amazing About page is to figure out what you want the page to say about your company. You then must grab the attention of the reader, boast a bit, tell a story and let others brag about you. With a little bit of thought…
In this Micro Tutorial viewers will learn how to create navigation buttons that change on rollover, using CSS (Continuation of the CSS Image Sprite tutorial) Create a parent ID for all the list items       - Specify position: absolute and display: block…
In this tutorial viewers will learn how to style a corner ribbon overlay for an image using CSS Create a new class by typing ".Ribbon":  Define the class' "display:" as "inline-block": Define its "position:" as "relative": Define its "overflow:" as …
Suggested Courses

749 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