0

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.

8
  • What is your HTML - do you have a select or optgroup tag with an ID of Optionen? Commented Jan 6, 2013 at 15:49
  • The reason you have received an error is because you are using a crap "tutorial" (if people would call it that) site, check www.w3fools.com Commented Jan 6, 2013 at 15:49
  • @PassKit i have an div in the select tag with the id Optionen Commented Jan 6, 2013 at 15:51
  • 1
    A div should not be inside an select tab. You are adding an option tag so this should go inside a select or optgroup tag. Your code will replace all html inside the Optionen container. Commented Jan 6, 2013 at 15:56
  • @PassKit i gave the select tag now the id optionen and it worked thanks can you write an answer so i can give you the points? Commented Jan 6, 2013 at 16:02

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.