/    Sign up×
Community /Pin to ProfileBookmark

Upgraded ajax – return var from stateChanged()

Hello all,
I’m going to try to keep my question short. You know that ajax code that everyone has …

[code=html]
var url=page+”.php”
url=url+”?sid=”+Math.random()
url=url+”&”+passvar
xmlHttp=GetXmlHttpObject(function(){stateChanged(str);})
xmlHttp.open(“GET”,url,true)
xmlHttp.send(null)
return whatreturn;
[/code]

When I call it through a function I want it to return the xmlHttp.responseText text.

So lets say I use the function below (ajax) contains the above code. I want it to alert what my php file echo’s.

[code=html]
function activate_menu() {
var whatreturn2 = ajax();
alert(whatreturn2);
}
[/code]

I’ve tried global variables every which way. Can someone please help! All my code is below – THANKS!

[code=html]var xmlHttp;
var whatdiv;
var whatreturn = “”;

function slide_ajax(page,passvar,div)
{
whatdiv = div;
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert (“Browser does not support HTTP Request”)
return
}
var url=page+”.php”
url=url+”?sid=”+Math.random()
url=url+”&”+passvar
xmlHttp=GetXmlHttpObject(function(){whatreturn = stateChanged(str);})
xmlHttp.open(“GET”,url,true)
xmlHttp.send(null)
return whatreturn;
}

function stateChanged(str)
{
if (xmlHttp.readyState==4 || xmlHttp.readyState==”complete”)
{
whatreturn = xmlHttp.responseText;
if (whatdiv != false){
var randomstring = String.fromCharCode(97 + Math.round(Math.random() * 25));
var newdiv = document.createElement(randomstring);
var ctrl;
ctrl = document.getElementById(whatdiv);
removeChildNodes(ctrl);
newdiv.innerHTML = whatreturn;
var container = document.getElementById(whatdiv);
container.appendChild(newdiv);
}
return whatreturn;
}
}

function removeChildNodes(ctrl)
{
if (whatdiv != false){
while (ctrl.childNodes[0])
{
ctrl.removeChild(ctrl.childNodes[0]);
}
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
}
return xmlHttp;
}[/code]

to post a comment
JavaScript

11 Comments(s)

Copy linkTweet thisAlerts:
@DokSep 09.2008 — Change
[CODE]xmlHttp=GetXmlHttpObject(function(){whatreturn = stateChanged(str);})[/CODE]
to
[CODE]xmlHttp=GetXmlHttpObject();
xmlHttp.onreadystatechange = stateChanged;[/CODE]

You might want to read this Ajax tutorial
Copy linkTweet thisAlerts:
@JutboyauthorSep 09.2008 — Thanks for the reply.

The reason I have the function call the way it is, is so I can pass variables to it.

The code I posted was to show my feeble attempt at trying to get the slide_ajax() to return a variable. (Also, I noticed that my call said just ajax, I changed it for this post and in my real code it says slide_ajax)
Copy linkTweet thisAlerts:
@DokSep 09.2008 — The reason I have the function call the way it is, is so I can pass variables to it.[/QUOTE]Ajax don't work that way. If you haven't got a function assigned for the onreadystatechange (which you don't) then you will not be able to read the Ajax response.

Read the tutorial I posted in my previous answer - it should clear things up.
Copy linkTweet thisAlerts:
@JutboyauthorSep 09.2008 — I apologize for my ignorance. I skimmed over the article the first time and read it in more detail again.

My code works perfect if I remove "whatreturn = " from...

[code=html]
xmlHttp=GetXmlHttpObject(function(){whatreturn = stateChanged(str);})
[/code]


I wish just trying to show my failed attempt. If I remove "whatreturn = " it allows me to pass a string to stateChanged. So thats not what I'm having problems with.

What I can't do is get "whatreturn" which gets assigned perfectly in stateChanged into slide_ajax function so I can return it to activate_menu() and use it as I please.

I realize I'm missing something, but I'm guessing its how global vars work in javascript. I appreciate your help and patience very much.
Copy linkTweet thisAlerts:
@DokSep 09.2008 — There are clearly something conceptually wrong with what you are doing
My code works perfect if I remove "whatreturn = " from...[CODE]xmlHttp=GetXmlHttpObject(function(){whatreturn = stateChanged(str);})[/CODE][/QUOTE]
The GetXmlHttpObject function does not accept any arguments? Why do you want to pass an argument to a function that doesn't make use of any arguments?

When calling GetXmlHttpObject(function(){whatreturn = stateChanged(str);}) this is what happens

1: stateChange is executed passing the variable str.

2: stateChange doesn't make use of any arguments so whatever were in str is now lost

3: stateChange will fail when trying to reference xmlHttp.readyState as you the xmlHttp is yet to be created and is null.

This sequence of commands
[CODE]url=url+"?sid="+Math.random()
url=url+"&"+passvar
xmlHttp=GetXmlHttpObject(function(){whatreturn = stateChanged(str);})
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
return whatreturn;[/CODE]

will send the XHR but as it is a asynchronous request the block will finish executing before you recieve the response. So whatreturn is whatever it was before the function call.

Doing it this way will never change whatreturn from what you initialized it to be.

Here is a simplified example of how it works
[CODE]// Glabal variables
var xmlHttp = null;
var whatreturns = ';

// Function for setting up a request and sending it
function send() {
xmlHttp=GetXmlHttpObject();
xmlHttp.open("GET",myURL,true)
// Set which function should handle the response
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.send(null)
}

// Here is the function for recieving the anwser
// It doesn't accept any arguments.
function stateChange() {
if (xmlHttp.readyState == 4)
whatreturns = xmlHttp.responseText;
}[/CODE]

When you execute send the following happens

1: An XHR object is created

2: A request is send

3: The send() function returns before the answer is recieved

4: When the answer is recieved the stateChanged function is executed and will store the response in the global variable whatreturns.
Copy linkTweet thisAlerts:
@JutboyauthorSep 09.2008 — Wow, thank you so much for such a detailed response. I understand my mistake and have corrected it using...

[code=html]
xmlHttp.onreadystatechange=function(){stateChanged(str)};
[/code]


instead of

[code=html]
xmlHttp=GetXmlHttpObject(function(){whatreturn = stateChanged(str);})
[/code]


since this won't work....

[code=html]
xmlHttp.onreadystatechange=function(){whatreturn = stateChanged(str);
[/code]


I tried a different approach...

[code=html]
var url=page+".php"
url=url+"?sid="+Math.random()
url=url+"&"+passvar
xmlHttp.passedinfo="";
xmlHttp=GetXmlHttpObject();
xmlHttp.onreadystatechange=function(){stateChanged(str)};
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
alert(whatreturn);
alert(xmlHttp.passedinfo);
}

function stateChanged(str)
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
whatreturn = str+xmlHttp.responseText;
xmlHttp.passedinfo = whatreturn;
}
}
[/code]


the first alert comes back undefined/empty. The second alert works perfect. However, if I remove the whatreturn alert the xmlHttp.passedinfo alert stops working. If it works with both alerts, it must be possible....right?
Copy linkTweet thisAlerts:
@A1ien51Sep 09.2008 — You are dealing with an asynchronous request. It fires off code and than it keeps chugging.

If you need the data right away you need to look at making a synchronous call or redesign your code to call the next step in the process. [Personally I would never use a synchronous call]

Eric
Copy linkTweet thisAlerts:
@JutboyauthorSep 09.2008 — Thanks for the reply Eric,

Do you think you could point me in the right direction for either making a synchronous call or redesign your code.

Thanks a million - Justin
Copy linkTweet thisAlerts:
@JutboyauthorSep 10.2008 — Whups, I forgot to say please.

Please
Copy linkTweet thisAlerts:
@DokSep 10.2008 — I would advise you to read a detailed tutorial on how AJAX works. There a plenty of good ones out there. These suggestions from google should get you started. http://www.google.dk/search?q=ajax+tutorial
Copy linkTweet thisAlerts:
@mezukhanJun 23.2009 — I found that this topic is quite related to my problem

i have multiple requests per page which are keep calling every after some seconds... i cant use same global variable for all of those what should i do now...

<html>

<head>


<script type="text/javascript">

var xmlhttp;

var idp;

function Ping(id,ip)

{

//alert("i am in ping my id is " + id + " and my ip is " + ip);


xmlhttp=GetXmlHttpObject();

if (xmlhttp==null)

{

alert ("Browser does not support HTTP Request");
return;
}
var url="ping_devices.php";
url = url + "?ip=" + ip;
url=url+"&sid="+Math.random();
idp = id;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);


}

function stateChanged()

{

if (xmlhttp.readyState==4)
{
//alert(idp . "=" . xmlhttp.responseText);
document.getElementById(idp).innerHTML=xmlhttp.responseText;

}

}

function GetXmlHttpObject()

{

if (window.XMLHttpRequest)

{

// code for IE7+, Firefox, Chrome, Opera, Safari

return new XMLHttpRequest();

}

if (window.ActiveXObject)

{

// code for IE6, IE5

return new ActiveXObject("Microsoft.XMLHTTP");

}

return null;

}

</script>

<script language='javascript'>

var time = 10;

var interval = time * 1000;

var timer1= setInterval("Ping(1, '172.16.12.182')", interval);

var timer2= setInterval("Ping(2, '172.16.12.1')", interval);

var timer3= setInterval("Ping(3, '172.16.50.9')", interval);

</script>

</head>

<body>

<label>

<input type="button" value="Click me!" onclick="test()" />

</label>

<table border='1'>

<tr>

<th>Device Name</th>

<th>IP Address</th>

<th>Acceptable Delay</th>
<th>Current Delay</th>
</tr>
<tr>
<td>SMSGateway</td>
<td>172.16.12.182</td>
<td>200</td>
<td><div id='1'>TEST</div></td>
</tr>
<tr>
<td>DefaultGateway</td>
<td>172.16.12.1</td>
<td>200</td>
<td><div id='2'>TEST</div></td>
</tr>
<tr>
<td>PrivateVilla</td>
<td>172.16.50.9</td>
<td>200</td>
<td><div id='3'>TEST</div></td>
</tr>

</table>

</body>

</html>
×

Success!

Help @Jutboy spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...