PDA

View Full Version : oop ajax calls (this.xmlhttp.readystate)


stick_branch
04-28-2009, 11:04 AM
Hi guys,

I've been making some OOP AJAX, and I've been having a little trouble with a few calls...

This JS errors on "if (this.xmlHttp.readyState == 4)" saying that "this.xmlHttp is undefined.... I don't understand why, as I call it in multiple other places. I can give an example if needed.

function create_ajax_request(){
this.xmlHttp;
try {
this.xmlHttp = new XMLHttpRequest();
}
catch (e) {
try {
this.xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
}

function send_ajax_request_post(){
this.xmlHttp.open("POST", this.ssurl, true);
this.xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
this.xmlHttp.setRequestHeader("Content-length", this.pdata.length);
this.xmlHttp.setRequestHeader("Connection", "close");
this.xmlHttp.send(this.pdata);
this.xmlHttp.onreadystatechange = function(){
if (this.xmlHttp.readyState == 4) {
if (this.xmlhttp.status == 200) {
this.request_done();
}
}
};
}

What happens is a class is initialized:

function ajax_add_comment(int_id,int_cid,str_comment_type)
{
this.add = function()
{
this.create_request();
this.send_post();
if(this.cid==0)
{document.getElementById('comment_box').innerHTML='<span class="subhead">Adding Comment</span><br><br>';}
};
this.ssurl = "/ajax/ajax_add_comment.php";
this.pdata = "type="+str_comment_type+"&id="+int_id+"&comment="+"test"+"&commentid="+int_cid+"&cache="+Math.random();// Data sent to xmlHttp.send
this.cid = int_cid;
this.create_request = create_ajax_request;
this.send_post = send_ajax_request_post;
this.request_done = function()
{
alert('Request Completed');
}
}

And when after being created, this.add() is called, which does the rest of the work. I've got the same ajax working NOT in an OOP context, but i'm looking at streamlining my code and hoped this would do a good job of it.

A1ien51
04-30-2009, 06:17 AM
It is because when the Ajax call comes back it is in a different scope.

this relates to the Ajax callback scope and not your functionality.

You really should use a JS Framework which takes car of all of this for you already. lol


If you want your code to work:

var that = this;
this.xmlHttp.onreadystatechange = function(){
if (that.xmlHttp.readyState == 4) {
if (that.xmlhttp.status == 200) {
that.request_done();
}
}
};


Eric

stick_branch
04-30-2009, 12:09 PM
Yeah I always knew that I *should*, but I wanted to create a lighter weight one.

Thanks a lot for that, I wasn't sure as to why it wasn't working.