Jump to content

help with an AJAX class


bennyboywonder

Recommended Posts

I am currently developing an ajax based website. Currently all the xmlHttp calls are handled by one function and a couple of big SWITCH statements inside it, which I think is quite an ugly way of doing it. Am trying to rewrite it with a class, but it doesn't seem to work. Here's the class

function htRequest(page, query) {
this.constructUrl = function() {
	if(this.query) this.url = this.page;
	else this.url = this.page + "?" + this.query;
}
this.send = function() {
	this.constructUrl();
	this.xhReq = createXMLHttpRequest();
	this.xhReq.open("GET", this.url, true);
	this.xhReq.onreadystatechange = this.onLoad;
	this.xhReq.send(NULL);
	this.whileLoading();
}
this.page = page;
this.query = query;
this.constructUrl();
}

 

then when I want to use it, the idea is I do something like this,

htr = new htRequest("xmlHTTP.php");
htr.whileLoading = function() {
// Loading code here
}
htr.onLoad = function() {
// What to do with the date when finished loading it here
}
htr.send();

then when I need to reuse the same call, but with different input data

htr.query = "string1=blah&string2=blah";
htr.send();

 

This does not seem to work however, and I can't figure out why. My knowledge of javascript is a bit gappy, so any help would be appreciated.

Link to comment
https://forums.phpfreaks.com/topic/40058-help-with-an-ajax-class/
Share on other sites

Ok well I have solved my original problem, but now I notice that when I try to call this.onLoad(); inside the onreadystatechange handler it doesn't work. Anyone have any clues why?

 

function htRequest(page, query)
{
    this.constructUrl = function() {
    {
        if(!this.query) this.url = this.page;
        else this.url = this.page + "?" + this.query;
    }

    }
    this.send = function()
    {
        this.constructUrl();
        http = createXMLHttpRequest();
        http.open("GET", this.url, true);
http.onreadystatechange = function()
        {
            
            if (http.readyState != 4)
            {
                return;
            } 
            
            if (http.status != 200)
            {
                return;
            }
            this.onLoad();
        }
http.send(null);
this.whileLoading();
    }
    this.page = page;
    this.query = query;
    this.constructUrl();
}

htr = new htRequest("xmlHTTP.php");

htr.whileLoading = function()
{
    alert("loading");
}

htr.onLoad = function()
{
    alert("loaded");
}

htr.send();

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.