Current location: Hot Scripts Forums » General Web Coding » JavaScript » Unknown Javascript/Ajax problem


Unknown Javascript/Ajax problem

Reply
  #1 (permalink)  
Old 06-01-09, 07:29 AM
vitron's Avatar
vitron vitron is offline
Newbie Coder
 
Join Date: Mar 2009
Location: Bradford
Posts: 27
Thanks: 0
Thanked 0 Times in 0 Posts
Exclamation Unknown Javascript/Ajax problem

Hi there guys
Im making a javascript tool for my site, and I thought Id make the tool portable (I can easily drag it from my current project, and with little effort, add it into another project), so I decided to add new ajax function set to it, so it wont get any ajax problems if my new project doesn't use ajax. The problem is, its returning nothing, and sometimes it returns 'undefined'. I've isolated the problem to when it gets a response, but cant figure out what the problem is.

Ajax Source Code:-
Code:
function runAjaxTask(){
	this.randomString = randomString;
	this.NewXmlHttpObject = NewXmlHttpObject;
	this.getContent = getContent;
	
	function randomString(maxLength){
		var chars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
		var stringLength = maxLength;
		var outputString;
		var i = 0;
		while(i < stringLength){
			outputString += chars[Math.round(Math.random()*35)];
			i++;
		}
		return outputString.replace("undefined","");
	}
	function NewXmlHttpObject(){
		var newxmlhttp = null;
		try {
			newxmlhttp = new XMLHttpRequest();
		}
		catch(ie){
			try {
				newxmlhttp = new window.ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e){
				newxmlhttp = new window.ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		if(newxmlhttp === null){
			alert("Your browser does not support AJAX!");
			return 0;
		} else {
			return newxmlhttp;
		}
	}
	function getContent(url,toid){
		var xmlhttp = this.NewXmlHttpObject();
		var ajaxURL = url+'&rid='+this.randomString(20);
		xmlhttp.open("GET", ajaxURL, true);
		xmlhttp.onreadystatechange = function(){
			if (xmlhttp.readyState === 4){
				if(xmlhttp.status === 200){
					var ajaxResponse = xmlhttp.responseText;
					document.getElementById(toid).innerHTML = ajaxResponse;
				} else {
					document.getElementById(toid).innerHTML = "Problem retrieving data (URL: "+ajaxURL+"):-" + xmlhttp.statusText;
				}
			}
		};
		xmlhttp.send(null);
	}
}
//var ajax = new runAjaxTask();
hope someone can help me, and quick please, im actually running past my deadline for this project, so I need to fix this problem quick
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #2 (permalink)  
Old 06-01-09, 08:33 AM
job0107's Avatar
job0107 job0107 is offline
Community Liaison
 
Join Date: Dec 2006
Location: Tacoma, Washington USA
Posts: 3,454
Thanks: 0
Thanked 140 Times in 137 Posts
This line of code:
Code:
if(newxmlhttp === null){
Should be:
Code:
if(newxmlhttp == null){
Generally when you pass GET values, the first one starts with a question mark.
So I would assume this line of code:
Code:
var ajaxURL = url+'&rid='+this.randomString(20);
Should be:
Code:
var ajaxURL = url+'?rid='+this.randomString(20);
Unless you are including the first name/value pair with the url variable.

And these two lines of code have the same problem as the first problem:
Code:
if (xmlhttp.readyState === 4){                
           if(xmlhttp.status === 200){
Should be:
Code:
if (xmlhttp.readyState == 4){                
           if(xmlhttp.status == 200){
__________________
Jerry Broughton
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #3 (permalink)  
Old 06-01-09, 09:16 AM
vitron's Avatar
vitron vitron is offline
Newbie Coder
 
Join Date: Mar 2009
Location: Bradford
Posts: 27
Thanks: 0
Thanked 0 Times in 0 Posts
The reason my if statements all have '===' is because its the correct javascript syntax, but it really doesn't matter if you use '==' or '===', I use it because I want to make sure my code runs perfectly on as many javascript browsers as possible
and yes, '?' is always sent to 'ajaxURL' by 'url' in my scripts:-
Code:
var ajax = new runAjaxTask();
ajax.getContent('run.php?task=checkprofiles&action=run','statusBox');
also, I forgot to mention in the first post, but my code is 100% syntax correct, so there is no errors in the way my coed has been displayed
if you don't believe me, check out using this tool:- JavaScript Lint
if you run my code with '==' instead of '===' you get the error messag:
Quote:
lint warning: comparisons against null, 0, true, false, or an empty string allowing implicit type conversion (use === or !==)
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #4 (permalink)  
Old 06-02-09, 12:21 AM
job0107's Avatar
job0107 job0107 is offline
Community Liaison
 
Join Date: Dec 2006
Location: Tacoma, Washington USA
Posts: 3,454
Thanks: 0
Thanked 140 Times in 137 Posts
Quote:
The problem is, its returning nothing, and sometimes it returns 'undefined'.
The only way I have been able to get it to return 'undefined' is if I don't assign any value to "var ajaxResponse"

And if I assign a value to it, "var ajaxResponse = xmlhttp.responseText;",
the worst I get back is nothing.
Unless run.php doesn't exist, then I get back "Problem retrieving data (URL: run.php?task=checkprofiles&action=run&rid=tcjsloup 65e2omqccqx1):-Not Found".

So the problem doesn't seem to be in this bit of code.
__________________
Jerry Broughton
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #5 (permalink)  
Old 06-02-09, 01:09 AM
job0107's Avatar
job0107 job0107 is offline
Community Liaison
 
Join Date: Dec 2006
Location: Tacoma, Washington USA
Posts: 3,454
Thanks: 0
Thanked 140 Times in 137 Posts
Quote:
Originally Posted by vitron View Post
The reason my if statements all have '===' is because its the correct javascript syntax, but it really doesn't matter if you use '==' or '===', I use it because I want to make sure my code runs perfectly on as many javascript browsers as possible
and yes, '?' is always sent to 'ajaxURL' by 'url' in my scripts:-
Code:
var ajax = new runAjaxTask();
ajax.getContent('run.php?task=checkprofiles&action=run','statusBox');
also, I forgot to mention in the first post, but my code is 100% syntax correct, so there is no errors in the way my coed has been displayed
if you don't believe me, check out using this tool:- JavaScript Lint
if you run my code with '==' instead of '===' you get the error messag:
This warning only applies to this line of code:
Code:
if(newxmlhttp === null){
It does not apply to these lines:
Code:
if (xmlhttp.readyState == 4){
                if(xmlhttp.status == 200){
And this is valid code because you use the 'not' operator to check for a null value.
The 'not' operator is not a type comparison, it checks for a Boolean 'true (any value besides null or 0)' or 'false (null or 0)' :
Code:
if(!newxmlhttp){
But in either case, your code will run either way.
__________________
Jerry Broughton

Last edited by job0107; 06-02-09 at 01:17 AM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #6 (permalink)  
Old 06-02-09, 06:39 AM
vitron's Avatar
vitron vitron is offline
Newbie Coder
 
Join Date: Mar 2009
Location: Bradford
Posts: 27
Thanks: 0
Thanked 0 Times in 0 Posts
Thanks for your help Jerry
but it seems the problem must be the way im calling the ajax functions i think, and because of that the problem occurs at:-
Code:
var ajaxResponse = xmlhttp.responseText;
document.getElementById(toid).innerHTML = ajaxResponse;
it seems that because of the way Im calling the ajax function (im calling it through another javascript function/class that I cant display here), when it trys saving the returned content to "document.getElementById(toid).innerHTML" it doesn't actually do it, so when my other code looks for the content in "document.getElementById(toid).innerHTML", it doesn't find anything and returns nothing then

Last edited by vitron; 06-02-09 at 06:44 AM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #7 (permalink)  
Old 06-02-09, 09:22 AM
job0107's Avatar
job0107 job0107 is offline
Community Liaison
 
Join Date: Dec 2006
Location: Tacoma, Washington USA
Posts: 3,454
Thanks: 0
Thanked 140 Times in 137 Posts
First make sure run.php is echoing something back.
And if it is, then you may have to use setTimeout() to delay any further actions until the response has been received.

Depending on server traffic, the returned response could take more time then you are allowing.
As I have found out, without a delay, trying to fetch the returned response from the recipient object can be hit and miss.

Without understanding what exactly you are doing, it is impossible for me to know where the problem is.
__________________
Jerry Broughton

Last edited by job0107; 06-02-09 at 09:26 AM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #8 (permalink)  
Old 06-02-09, 09:26 PM
job0107's Avatar
job0107 job0107 is offline
Community Liaison
 
Join Date: Dec 2006
Location: Tacoma, Washington USA
Posts: 3,454
Thanks: 0
Thanked 140 Times in 137 Posts
This may be a little simplified but this code creates the runAjaxTask() object that fetches a task and displays it in div1.
Then the runAjaxTask() object creates the transferAjaxTask() object that transfers a copy of the task from div1 to div2.
This code works seamlessly because the transferAjaxTask() object doesn't get created until there is a valid response from AJAX.

HTML Code:
<script>
function runAjaxTask()
{
 this.randomString = randomString;
 this.NewXmlHttpObject = NewXmlHttpObject;
 this.getContent = getContent;
 this.results = results;
 function results()
 {
  return this.getContent;
  }
 function randomString(maxLength)
 {
  var chars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
  var stringLength = maxLength;
  var outputString;
  var i = 0;
  while(i < stringLength)
  {
    outputString += chars[Math.round(Math.random()*35)];
    i++;
    }
  return outputString.replace("undefined","");
  }
 function NewXmlHttpObject()
 {
  var newxmlhttp = null;
  try {newxmlhttp = new XMLHttpRequest();}
  catch(ie){try {newxmlhttp = new window.ActiveXObject("Msxml2.XMLHTTP");}
            catch(ie){newxmlhttp = new window.ActiveXObject("Microsoft.XMLHTTP");}
              }
  if(newxmlhttp === null)
  {
    alert("Your browser does not support AJAX!");
    return 0;
    }
  else{return newxmlhttp;}
  }
 function getContent(url,toid,transtoid)
 {
  var xmlhttp = this.NewXmlHttpObject();
  var ajaxURL = url+'&rid='+this.randomString(20);
  xmlhttp.open("GET", ajaxURL, true);
  xmlhttp.onreadystatechange = function()
  {
    if(xmlhttp.readyState == 4)
   {
     if(xmlhttp.status == 200)
    {
      var ajaxResponse = xmlhttp.responseText;
      document.getElementById(toid).innerHTML = ajaxResponse;
      var initialize = new transferAjaxTask();
     initialize.transfer(toid,transtoid);
      }
    else{document.getElementById(toid).innerHTML = "Problem retrieving data (URL: "+ajaxURL+"):-" + xmlhttp.statusText;}
     }
   };
  xmlhttp.send(null);
  }
 }
function transferAjaxTask()
{
 this.transfer = transfer;
 function transfer(obj1,obj2){document.getElementById(obj2).innerHTML = document.getElementById(obj1).innerHTML;}
 }
</script>
<body>
<div id="div1" style="border:1px solid #000;"></div>
<div id="div2" style="border:1px solid #f00;"></div>
<script>
var ajax = new runAjaxTask();
ajax.getContent('run.php?task=checkprofiles&action=run','div1','div2');
</script>
</body>
__________________
Jerry Broughton

Last edited by job0107; 06-02-09 at 09:36 PM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #9 (permalink)  
Old 06-04-09, 09:23 AM
Vicious's Avatar
Vicious Vicious is offline
Community VIP
 
Join Date: Jan 2007
Location: Belgium
Posts: 584
Thanks: 0
Thanked 0 Times in 0 Posts
Quote:
Originally Posted by job0107 View Post
This line of code:
And these two lines of code have the same problem as the first problem:
Code:
if (xmlhttp.readyState === 4){                
           if(xmlhttp.status === 200){
Should be:
Code:
if (xmlhttp.readyState == 4){                
           if(xmlhttp.status == 200){
=== makes sure there is no type conversion (also known as explicit type check):
Code:
var myvar = "4";
if (myvar == 4){ alert("hmm, string converted to integer");}
if (myvar ===4){ alert("this alert shouldn't be shown");}
If you run that in firebug, you'll see what happens.
__________________
Jack Bauer makes Chuck Norris cry
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #10 (permalink)  
Old 06-05-09, 12:44 PM
vitron's Avatar
vitron vitron is offline
Newbie Coder
 
Join Date: Mar 2009
Location: Bradford
Posts: 27
Thanks: 0
Thanked 0 Times in 0 Posts
Thanks for your help on this jerry, your suggestion about setTimeout() is what fixed the problem for me
(I know its a late reply, just thought Id say thanks )
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
Reply

Bookmarks

Tags
ajax, framework, javascript


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Hai please anyone help me in solving this task inpython programming language durgaramesh Other Languages 1 06-13-08 02:20 AM
Problem with session in php5 cty PHP 1 12-09-06 06:42 AM
unknown problem - probably $session issue clantron PHP 6 03-19-06 02:36 PM
Asp and Microsoft Access 2002 problem gop373 ASP 2 10-06-04 10:13 AM
unknown problem with upload script rush989 PHP 3 08-31-04 02:56 AM


All times are GMT -5. The time now is 12:32 PM.
vBulletin® Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.