Forum Moderators: open

Message Too Old, No Replies

JS Global Vars when using AJAX

Losing variables when using AJAX

         

colandy

9:17 am on May 30, 2007 (gmt 0)

10+ Year Member



I have a little issue that's causing me some grief, well a lot of grief really so just wondering if someong can help.

Here's an example script that's causing me issues:

<script ........>
var browser=navigator.appName;
var catCount=0;

function drawpage()
{
var mdiv=getElementById('mainpage');
mdiv.innerHTML=browser+" "+catCount;
}

function getdata()
{
var catObj=new ajaxObject('getdata.php',setVars);
catObj.update();
}

function setVars(responseText, responseStatus)
{
if(responseStatus==200)
{
catCount=responseText;
}
}

function initialise()
{
getData();
drawpage();
}

window.onload=initialise;
</script>

OK, now the issue is surrounding the catCount variable, browser is fine but the catCount variable always returns zero, however the responseText returns 3.

The ajaxObject is just a little routine I have that creates the HTTPRequest calls the php page and returns the relevant data in responseText.

This really is a pretty str8 forward bit of script but for the life of me I can't see where I'm going wrong.

mehh

9:27 am on May 30, 2007 (gmt 0)

10+ Year Member



var mdiv=getElementById('mainpage');

thats wrong though probably not what your looking for
var mdiv=document.getElementById('mainpage'); 

also try this


function setVars(responseText, responseStatus)
{
if(responseStatus==200)
{
catCount=responseText;
alert(catCount)
drawpage();
}
}

colandy

9:33 am on May 30, 2007 (gmt 0)

10+ Year Member



sorry, me being lazy, forgot to put in the document object in the above, but is in the code.

That works, but my question now is...... Why?

The only reason I ask is that I will have another ajaxObject call for more data that's required for other global vars.

*** Thanks for the quick response ***

mehh

12:03 pm on May 31, 2007 (gmt 0)

10+ Year Member



what you where doing is calling drawpage() before the ajax has loaded.
quick diagram

____JS______ ____functions___ _____AJAX____
getData()----->Load The ajax----->loading
next <-------- I'm Finished__ ¦_____ ¦
drawPage()----> catcount is 0 ¦_____ ¦
catcount =3 <-----------------------Done

I hope that is clear