I am new to AJAX. Could someone please help me with this problem.. its kind of urgent for me to get this working.
I have a form which when submitted should create an XMLHttpRequest to send the form values to a PHP script. Below is my code for the request.
On IE I get an error saying 'Type Mismatch' at xmlHttp.onreadystatechange=stateChanged(id);
As you can see in my function stateChanged(id) I have an else statement to check xmlHttp.readyState. This shows as '0', so the request is not getting initialized. What do I need to change?
Thanks!
Code:
var xmlHttp
function save(id)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var name = $("desc"+id).value;
var capacity = $("capacity"+id).value;
var equipid = $("equip"+id).value;
var params = 'desc='+name+'&capacity='+capacity+'&id='+equipid;
xmlHttp.onreadystatechange=stateChanged(id);
xmlHttp.open("POST","trialsubmit.php",true);
xmlHttp.send(params);
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function stateChanged(id)
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
$("name"+id).innerHTML=xmlHttp.responseText;
}
else
{
$("name"+id).innerHTML=xmlHttp.readyState;
}
}
To further elaborate on what Waqas_Badar wrote, doing the following assignment:
Code:
xmlHttp.onreadystatechange = stateChanged(id);
will run stateChanged(id) immediately and assign its return value to xmlHttp.onreadystatechange. To assign a variable to a reference to a function instead of the return value of a function, you can't use parentheses:
Code:
xmlHttp.onreadystatechange = stateChanged;
If you have to pass values to the function, you should do what Waqas_Badar suggested:
Code:
httpReq.onreadystatechange = function () { stateChanged(id); };
I generally avoid setting properties of objects I haven't constructed myself (unless they're actually proper extensions to those objects.) I'd rather go with a manager class if there's more complex variable sending going on:
Code:
var Request = function (id) {
this.id = id;
};
Request.prototype = {
id: -1,
stateChange: function () {
// thanks to call(), "this" refers to the current instance.
// ...
},
send: function () {
var http = GetXmlHttpObject();
var t = this;
http.onreadystatechange = function () { t.stateChange.call(t); };
// Use instance variables here...
http.open("GET", "index.html", true);
http.send("");
}
};
var req = new Request(10);
req.send();
Bookmarks