JS variable undefined - must be brain fart

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

JS variable undefined - must be brain fart

Post 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?
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post 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)
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply