Ajax / php中的错误

Hey guys im trying to add to my site some ajax code. I know php but ajax is new for me so i used for an example on w3schools.com and changed some part of it. When i am using my script firebug gives me this error: TypeError: document.getElementById(...) is null. So what did i wrong i didn't know can you help me? This is my code:

function showOptionen(str)
{
if (str=="")
  {
  document.getElementById("Optionen").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
//Here in this line is the error:
    document.getElementById("Optionen").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","bezeichnungs-optionen.php?q="+str,true);
xmlhttp.send();
}

I checked my bezeichnungs-optionen.php and its result is: <option value="DELL Notebook">DELL Notebook</option> so it is everything ok with it.

You could try and call the function showOptionen(testStr) after the page has been loaded like this:

window.onload = function (){
    showOptionen(testStr);
}

It seems like when the function is called the element does not exist, so it might not have been loaded yet.

You could always use the jQuery library, which simplifies many javascript operations, including ajax.

Many browsers will reject innerHTML that results in invalid markup.

Since you are returning an <option> tag make sure that your 'Optionen' is a <select> or <optgroup> tag.