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.
-
What is your HTML - do you have a select or optgroup tag with an ID of Optionen?PassKit– PassKit2013年01月06日 15:49:35 +00:00Commented 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.comDaryl Gill– Daryl Gill2013年01月06日 15:49:54 +00:00Commented Jan 6, 2013 at 15:49
-
@PassKit i have an div in the select tag with the id OptionenAlesfatalis– Alesfatalis2013年01月06日 15:51:39 +00:00Commented Jan 6, 2013 at 15:51
-
1A 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.PassKit– PassKit2013年01月06日 15:56:06 +00:00Commented 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?Alesfatalis– Alesfatalis2013年01月06日 16:02:06 +00:00Commented Jan 6, 2013 at 16:02
2 Answers 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.
Comments
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.