Forum Moderators: open

Message Too Old, No Replies

Store responseText value to a global variable in JavaScript

Is this possible?

         

bpejman

10:01 pm on Jul 14, 2009 (gmt 0)

10+ Year Member



Hi,

I have an AJAX function that simply calls a PHP file and receives a value from it. Here's the code:


var result = null;

httpobj = new XMLHttpRequest();
httpobj.open('get', 'file.php', true);
httpobj.send(null);
httpobj.onreadystatechange = function()
{
if (httpobj.readyState == 4 && httpobj.status == 200)
{
self.result = httpobj.responseText;
}
}

alert(self.result);

I declared a global variable called result that is visible throughout my javascript file. I then attempted to store the httpobj.responsetext to this variable but then after I did an alert after the function call, I received null.

After thinking about it, it makes sense because on onreadystatechange I'm calling a function that appear to have a "hidden" scope where global variables are not recognized, if that makes sense.

Also, any subsequent functions I call from within function() are also part of this "hidden" scope.

Does anyone know how I can store the value of responsetext to a variable that I've declared globally, in this case, result?

I do not want to store this into any HTML tags and retrieve it again but rather access the value directly from one variable to another.

Any ideas and help would be helpful and appreciated!

Bobby Pejman

whoisgregg

6:28 pm on Jul 15, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to WebmasterWorld, bpejman!

I'm not sure what other code might be at play here, but changing "self.result" to "this.result" and then alerting "httpobj.result" may work for you.

The alert will fire before your httpobj has received a response though, so you'll want to move the alert into the onreadystatechange function.

bpejman

10:11 pm on Jul 15, 2009 (gmt 0)

10+ Year Member



Hi,

Thanks for the reply! I did what you mentioned and still no luck. As an FYI, I purposely put the alert outside of the onreadystate function because I'd like to capture the result of responseText and store it within a global variable in the same javascript file.

The issue here is that I'm working with different scopes where one has no visibility to the other. Anything that falls into the function(){} scope vanishes once the function is ended. It also doesn't see any global variables once I enter the function scope. The sad news I'm hearing is that what I'm trying to do is impossible. At least, after countless hours of Googling.

Thanks for the reply again, though. If anyone has managed to solve this, it would really help me out!

john_k

6:16 pm on Jul 16, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Remove your alert. The first time it is executed will be BEFORE the onreadystatechange function has executed. And result will necessarily still be null.

Add an alert('testing') inside of the callback function to ensure that it is even executing.

Remove the "self." (or "this.") prefix from the result variable. If result is declared within the same <script> tag (or an earlier one) in the head of the document, and outside of any function, then it will be visible to the callback function.

If file.php has any logic in it right now, then replace it with a stripped down version that just returns a single value for testing purposes.

If the original code you posted has lines removed, then post the entire block.

bpejman

7:20 pm on Jul 16, 2009 (gmt 0)

10+ Year Member



John, many many thanks to you. Many hours of Googling and no one on the web caught this mistake. You solved my problem. :) This whole time I've been thinking that onreadystatechange halts the script execution until a response is returned. Now that I think about it, if that was true, it wouldn't be so asynchronous now would it? Thanks again! As a side question, wouldn't it help to resolve ambiguity between variables that are being used in different JS files by using self/this? I always thought it's safer to do this than not but I will have to read up on it.

Here's my new JavaScript code that captures and stores the value of responseText. Hopefully this will help others.


var interval;
var result = null; // Set this accordingly based on various return values from your PHP file
httpobj = new XMLHttpRequest(); //FF for now
httpobj.open('get', 'file.php', true);
httpobj.send(null);
httpobj.onreadystatechange = function()
{
if (httpobj.readyState == 4 && httpobj.status == 200)
{
result = httpobj.responseText;
}
}
interval = setInterval("getResult()", 1000);
// Alert the value of result and clear interval
function getResult()
{
// once we get a result, turn interval off.
if(result != null)
{
interval = clearInterval(interval);
alert(result); // we're clearly out of the onreadystatechange scope with our result.
}
}

cele

9:03 am on Aug 26, 2009 (gmt 0)

10+ Year Member



bpejman, please help me..
i got that problem too but i couldn't figure it out.. i've tried your code,but it didn't give value from my PHP file to the variable(result).
what is the function of setInterval? did you define it yourself or it's AJAX default function?
this is my code, any help would be appreciated..
var url = "javascript/time.php?q="+hypLinkL[2];
var xmlhttp = false;
var fileid = null;
var interval;
rhtml+='<td>';
xmlhttp = getXMLHttpRequest();
if(xmlhttp==null)
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState == 4)
{
fileid = xmlhttp.responseText;
}
}
interval = setInterval("getResult()", 1000);
function getResult()
{
// once we get a result, turn interval off.
if(fileid != null)
{
interval = clearInterval(interval);
alert(fileid); // we're clearly out of the onreadystatechange scope with our result.
}
};

bpejman

3:08 am on Aug 27, 2009 (gmt 0)

10+ Year Member



Hi Cele,

Ok, I reviewed your code and to answer your question, the setInterval() is a built-in JS function that executes at a specified millisecond interval. In this case, I have it set to check on the onreadystatechange so as soon as a result is returned by AJAX. It will check every second (1000 milliseconds) until a result is returned. I would recomend you reduce this number to 100. The result from Ajax is returned a lot faster so your program/function doesn't have to waste an entire second waiting.

Keep in mind that if you reduce it to a low number, it will cause the setInterval to execute at a much faster rate so consider that.

Also, you might want to take a look at setInterval(), setTimeout(), clearInterval() and so on because they will come in handy.

Now, I think what your problem is that you want to put "&& xmlhttp.readyState == 200" in your IF statement where readyState == 4. Simply having a readystate of 4 is not enough.

Also, take a look and make sure that the parameter you're passing in to your PHP file ("+hyperLink[2]) is being picked up. I don't know what's going on in your PHP file so I can't troubleshoot but if you're doing a $_Get['q'], you might want to make sure it's working.

Try that and let me know how it goes.