Firebug gives error "Ajax is not defined"
I have this HTML form which uses AJAX to pass data to a php file. (I did this so I don't have to leave the current page). Firebug gives me two errors :
document.getElementById("name") is null
ajaxget is not defined
I only started using AJAX today out of desperation, so I'm very new to it. The PHP file is second.php
, the important part is that it receives the variables so it can create an output to be used by another html later, but it doesn't have to respond back:
<html>
<head>
</head>
<body>
<script type="text/javascript">
function ajaxRequest(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++){
try{
return new ActiveXObject(activexmodes[i])
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
return new XMLHttpRequest()
else
return false
}
var mygetrequest=new ajaxRequest()
mygetrequest.onreadystatechange=function(){
if (mygetrequest.readyState==4){
if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=mygetrequest.responseText
}
else{
alert("An error has occured making the request")
}
}
}
var namevalue=encodeURIComponent(document.getElementById("name").value)
var agevalue=encodeURIComponent(document.getElementById("age").value)
mygetrequest.open("GET", "second.php?name="+namevalue+"&age="+agevalue, true)
mygetrequest.send(null)
</script>
<form method="get" action="">
Your name: <input type="text" id="name" name="name" size="25" /> <br />
Your age: <input type="text" id="age" name="age" size="25" /> <br />
<input开发者_开发问答 type="button" value="submit" onClick="ajaxget()" />
</form>
<div id="result"> </div>
</body>
</html>
document.getElementById("name") is null
You have var namevalue=encodeURIComponent(document.getElementById("name").value)
outside of any function. So it runs when the <script>
element is parsed — which is before the element with that id exists in the DOM.
ajaxget is not defined
You have onClick="ajaxget()"
but nowhere do you have any other mention of ajaxget
(such as function ajaxget() { …
<input type="button" value="submit" onClick="ajaxget()" />
^^^^^^^^^--- where is this function?
You do not have an ajaxget()
function defined in your code.
精彩评论