Page 1 of 1

JS variable undefined - must be brain fart

Posted: Wed Jul 20, 2005 12:04 pm
by pickle
Hi everyone,

For some reason, the answer to this problem is completely eluding me. I've written two Javascript functions - one needs to get the return value from the other. For some reason though, the first function seems to always be getting an 'undefined' error. Here's the setup:

Code: Select all

function main_nav_clean(id)
{
  var working_element = document.getElementById(id);
  var new_text = document.getElementById('new_text').value;
  var new_href = document.getElementById('new_href').value;
  var update_status = 'default';

  update_status = getXMLHTTP('/common/update_main_nav.php?id=' + id + '&text=' + new_text + '&href=' + new_href);

  alert(update_status);
}
That function calls this one:

Code: Select all

function getXMLHTTP(url_to_send)
{
  ...
  xmlhttp.open(&quote;GET&quote;, url_to_send, true);
  xmlhttp.onreadystatechange=function()
  {
    if(xmlhttp.readyState==4)
    {
      var ret_val = xmlhttp.responseText;
      return(ret_val);
      
    }
  }
}
If I call alert(ret_val) right before the return statement, I get the correct text. However, the alert in the first function will always pop up 'undefined' - even when I return 'test text' from my second function. Any ideas?

Posted: Wed Jul 20, 2005 5:00 pm
by Burrito
the only thing I can think of is maybe it's not getting the data back before you return the value. I know you said that you alert it and it looks correct, but perhaps when you don't have the alert, it's not completing the function.

try adding this to your getXMLHTTP function

Code: Select all

if(xmlhttp.readyState==4 && xmlhttp.status == 200)

Posted: Wed Jul 20, 2005 5:03 pm
by pickle
I tried goofing with it some more and broke it to the point where it wasn't even poping up the alert. I replace all the code and was still having that problem. So, I decided to keep my emotional state somewhat intact and moved on in another direction. Thanks though.