Solved

ajax request stuck on readyState

Posted on 2013-05-21
5
788 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

Question has a verified solution.

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

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Originally, this post was published on Monitis Blog, you can check it here . Websites are getting bigger and more complicated by the day. Video, images and custom fonts are all great for showcasing your product or service. But the price to pay in…
In this tutorial viewers will learn how to style transparent/translucent elements using alpha transparency in CSS Start with a normal styled element, such as a div.: Define its "background-color" property as "rgba (255, 255, 255, .5): The numbers in…
In this tutorial viewers will learn how to embed videos in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <video> tag to insert a video. Define the src as the URL of your video; this is similar to …

707 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