is it possible to use the xmlHTTP.responseText in any other java function, after execuation of stateChanged() function??? example in ajax...

function stateChanged(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
       var result = xmlHttp.responseText 		
        if (result.length=="0"){
        var task = "do";  //i want to use "task" in other js function
         return task; 
      }		
   }
}

i used many ways (a little bit i know) to do but could not get the success. how can we do???

any thoughts please......

Dani AI

Generated

Short answer: yes — but only after the XHR finishes. The important point missing from the thread is the asynchronous flow: starting a request returns immediately, so any code that depends on the server reply must run after the response arrives (not immediately after calling the request function). ’s fixes addressed the immediate bugs in the examples, and the remaining robust approaches avoid globals and race conditions.

A practical pattern (modern and concise) is to return a Promise and consume the response inside its then/catch handlers. This keeps the response text local and passes it to whatever function needs it:

function ajaxGet(url) {
  return fetch(url, { cache: 'no-store' })
    .then(resp => {
      if (!resp.ok) throw new Error('HTTP ' + resp.status);
      return resp.text();
    });
}

// usage:
ajaxGet('test3.php?id=42')
  .then(text => {
    const clean = text.trim();
    const task = clean ? 'correct' : 'incorrect';
    handleResult(task, clean); // call the next function here
  })
  .catch(err => console.error('AJAX failed:', err));

Quick troubleshooting checklist (useful years later):

  • Don’t call a checker function right after sending the request; call it from the XHR/fetch completion handler.
  • Trim responseText and watch for PHP notices/whitespace that make an “empty” response non-empty.
  • Inspect the Network tab to confirm response body and HTTP status.
  • If you expect structured data, return JSON and parse it (try/catch around JSON.parse or use resp.json()).
  • Avoid globals for response data; pass data into callbacks or return a Promise.
  • For older browsers, the same rule applies: run dependent code inside onload/onreadystatechange when the request is complete.

This approach prevents timing bugs like the ones discussed by and builds a clearer, maintainable flow.

Recommended Answers

All 11 Replies

Here's a simple demo -- on how to access variable(s) from another function:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html id="xhtml10S" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://www.w3.org/2005/10/profile">
<!--[if IE]>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<![endif]-->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title>Free Live Help!</title>
<script id="script15" type="text/javascript">
// <![CDATA[

var stateChanged = function() {
// Some statement 


   task = "do"; // Just don't use the "var" keyword when you declare the task variable, and you will be able to access this variable in other functions available in your program.
}();

var b = function() {
   return alert( "This call is from the b() function (" + task + ") is value of \"task\" variable inside the stateChanged() function." ); };

var c = function() {
   b();
   return alert( "This call is from the c() function (" + task + ") is the value of the \"task\" varible inside the stateChanged function." ); };

window.onload = c;

// ]]>
</script>
</head>
<body>

</body>
</html>

no luck sir....

Before you can access any of this variable, the function holding it must be initiated first.

And only the functions that comes next to the stateChange function can gain access to the task variable and those from above will ignore this call.
e.g.

var a = function() {
alert( task ); // Will output as undefined variable.

/* if you will access the task variable, within this function, the call will be ignored-- since this function comes first before the stateChange function. */ };

var stateChanged() {
task = "do";

// This function must be initiated first, to make the task variable availble, to the other function(s) accessing it.
}();

var b = function() {
return alert( task );

// The task variable is accessible inside this function, and so does with the other functions comes next to this.
};

sorry essential, i used every method including all the instructions given by you, but no success....

Ok, i'll provide you with another brief example later.

Are you accessing this variable inside your request handler?

Here's the code, and you'll need to provide your own test.txt file in replace of the ajax's url.

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<?xml-stylesheet type="text/css" href="#ccs21" media="all"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html id="xhtml10S" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://www.w3.org/2005/10/profile">
<!--[if IE]>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<![endif]-->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title>Free Live Help!</title>
<style id="css21" type="text/css" media="all">
/* <![CDATA[ */

samp:before, samp:after { content : '"'; }
samp, var { font : bold 9pt monospace; }
var:before { content : "var "; color : #800080; }
var { color : #00F; }
samp { color : #F00; }
/* ]]> */
</style>
<script id="script15" type="text/javascript">
// <![CDATA[

var req;
var handleRequest = function() { 
   if ( req ) {
   if ( req.readyState === 1 ) {
      // if ( req.status === 200 ) {
         task = "active"; // This value will be available if the user send active request.
      // }
      } 
   } else { task = "Inactive"; }
};

var sendRequest = function() {
   req = null;
   method = "GET";
   try {
      if ( window.XMLHttpRequest ) {
      req = new XMLHttpRequest();
   } else if ( window.ActiveXObject ) {
         try {
         req = new ActiveXObject("Microsoft.XMLHTTP");
         } catch( e1 ) {
         req = new ActiveXObject("Msxml2.XMLHTTP");
         }
      }
   } catch( e2 ) {
   (( window.createRequest ) ? req = window.createRequest() : req = null );
   }
   (( req.overrideMimeType ) ? req.overrideMimeType("text/xml") : req );
   if ( req !== null ) {             req.onreadystatechange = handleRequest;
   req.open( method, "[b]test.txt[/b]", true );
   (( req.setRequestHeader && method === "POST" ) ?  req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") : req ); 
   req.send( null );
   } else {
      alert("\nYour browser does not support AJAX Request!"); 
   }
};
var checkVar = function() {
   alert( task );
}
// ]]>
</script>
</head>
<body>
<div id="main">
<p>
This call don't use live request: <button id="btn" name="btn" onclick="handleRequest();checkVar();">Check <var>task</var></button><br /><br />
<var>task</var> will output as: <samp>Inactive</samp>.</p>
<hr />
<p>
This call uses live request: <button id="btn" name="btn" onclick="sendRequest();checkVar();">Check <var>task</var></button><br /><br />
<var>task</var> will output as: <samp>active</samp>.<br /><br />
Once the request has been initiated, <var>task</var> variable will preserved its value, into <samp>active</samp>
</p>
</div> 
</body>
</html>

its runnung very much fine....your solutions are always give me something different....thinking of doing things differently....

when i test the following....it does not respond...please can you help where i am comitting mistake...

<?php
session_start();
if ( !empty( $_GET['id'] )) 
{ 
   include("securimage.php");
   $img = new Securimage();
   $valid = $img->check( $_GET['id'] );
   if ($valid == true){
   $response = "Code is Correct"; 
   }
echo $response;
} else {
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html id="html4" lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<title>Live Help!</title>

<script type="text/javascript">
var req;
var handleRequest = function() { 
   if (req) {
   if (req.readyState == 4 || req.status == "complete") {
		respond = req.responseText;
        if ( respond.length === "0" ) {
        task = "incorrect"; // This value will be available if the user send active request.
        }
      } 
   } else { task = "correct"; }
};

var sendRequest = function(str) {
   if(str==""){alert("please enter the code"); return;}
   req = null;
   url = "test3.php?id=" + str;
   method = "GET";
   try {
      if ( window.XMLHttpRequest ) {
      req = new XMLHttpRequest();
   } else if ( window.ActiveXObject ) {
         try {
         req = new ActiveXObject("Microsoft.XMLHTTP");
         } catch( e1 ) {
         req = new ActiveXObject("Msxml2.XMLHTTP");
         }
      }
   } catch( e2 ) {
   (( window.createRequest ) ? req = window.createRequest() : req = null );
   }
   (( req.overrideMimeType ) ? req.overrideMimeType("text/xml") : req );
   if ( req !== null ) { 
   req.onreadystatechange = handleRequest;
   req.open( method, url, true );
   (( req.setRequestHeader && method === "POST" ) ?  req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") : req ); 
   req.send( null );
   } else {
   alert("\nYour browser does not support AJAX Request!"); 
   }
};

var checkVar = function() {
	if (task == "correct"){
   		alert("the script runs fine"); } else { alert("incorrect"); } 
}
// -->
</script>
</head>
<body>
   <form method="POST">
   <!-- pass a session id to the query string of the script to prevent ie caching -->
   <img src="securimage_show.php?sid=<?php /*><!--?*/ echo md5(uniqid(time())); /*--><?*/ ?>">
<br>
   <input type="text" name="code" onblur="sendRequest(this.value); checkVar();"/><br />
   <input type="submit" value="Submit Form" />
   </form>
  <div id ="response">Response will be display here!</div>
</body>
</html>
<?php 
} 
?>

thank you for the solutions....

Try raplacing the response status value into 200, instead of "complete" req.status === 200 . Let me know, if its still fails to work.

And also within your if block:

//if ( respond.length === "0" ) { // Replace this line with:

if ( respond.length === 0 ) { // This should work --> your next statement...

thank you very much.............its working now, after your advised ammendments.......

And you are always welcome, servis...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.