need help with generic ajax get function

L

lawpoop

I'm trying to write a generic ajax get function. I want to return the
response from the get request, so that I can reuse it in other
scripts. Perhaps I want to use it in an innerHtml, perhaps I want to
put it in an alert().

I have this, which works:

function ajaxGetResponse( page ) {

var xmlHttp;

try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp=new ActiveXObject
("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support
AJAX!");
return false;
}
}
}

xmlHttp.onreadystatechange=function() {
if ( xmlHttp.readyState == 4 ) {
alert ( xmlHttp.responseText );
}
}

xmlHttp.open( "GET", page, true );

xmlHttp.send(null);

}

In other words, I get an alert of the value of the page that I'm
requesting.

However, I tried simply changing alert() to return, and in IE, I get
an alert box which says simply "undefined".

function ajaxGetResponse( page ) {

var xmlHttp;

try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp=new ActiveXObject
("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support
AJAX!");
return false;
}
}
}

xmlHttp.onreadystatechange=function() {
if ( xmlHttp.readyState == 4 ) {
return xmlHttp.responseText ;
}
}

xmlHttp.open( "GET", page, true );

xmlHttp.send(null);

}

What am I doing wrong?
 
G

Gregor Kofler

lawpoop meinte:
However, I tried simply changing alert() to return, and in IE, I get
an alert box which says simply "undefined".

function ajaxGetResponse( page ) {

var xmlHttp;

try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp=new ActiveXObject
("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support
AJAX!");
return false;
}
}
}

xmlHttp.onreadystatechange=function() {
if ( xmlHttp.readyState == 4 ) {
return xmlHttp.responseText ;
}
}

xmlHttp.open( "GET", page, true );

xmlHttp.send(null);

}

What am I doing wrong?

(Could you puhleeze format your code in a more readable way?)

Not understanding "asynchronous"? I don't know when or how this alert
you are talking about is supposed to to called.

I assume you try something like

window.alert(ajaxGetResponse(...)); and it - expectedly - yields
undefined, since ajaxGetResponse returns undefined (no explicit return
value). The ORSC callback gets called at some undefined point of time in
the (near) future. Therefore ORSC has to invoke a function to process
the returned value.

Something like:
xmlHttp.onreadystatechange=function() {
if ( xmlHttp.readyState == 4 ) {
foo(xmlHttp.responseText);
}

and

var foo = function(val) {
window.alert(val);
}


Gregor
 
K

kouPhax

        xmlHttp.onreadystatechange=function() {
                if ( xmlHttp.readyState == 4 ) {
                        return xmlHttp.responseText ;
                }
        }
What am I doing wrong?

Think about what your __return__ statement is returning to? You need
to do something with your responseText not just return it.

xmlHttp.onreadystatechange=function() {
if ( xmlHttp.readyState == 4 ) {
ajaxComplete(xmlHttp.responseText);
}
}

Where ajaxComplete is a function that actually does the work you want
with your response text e.g.

function ajaxComplete(txt){
alert(txt);
}

Perhaps that's what you need?

James
 
L

lawpoop

Think about what your __return__ statement is returning to?

I'm wanting it to return to whatever script called it -- in other
words, a generic request gateway to server-side data.
 You need to do something with your responseText not just return it.

Perhaps this is where my understanding of javascript breaks down. If I
can alert() it, and I can divid.innerHtml it, why can't I return it?
        xmlHttp.onreadystatechange=function() {
                if ( xmlHttp.readyState == 4 ) {
                        ajaxComplete(xmlHttp.responseText);
                }
        }

Where ajaxComplete is a function that actually does the work you want
with your response text e.g.

    function ajaxComplete(txt){
        alert(txt);
    }

Perhaps that's what you need?

Well, I don't want to hard-code the function in the ajaxGetResponse.

In that case, why would I bother to make another function called
ajaxComplete()? Why not just do alert(xmlHttp.responseText); in the
original script?

I am looking to make a generic function that can get some data from
the server-side. I might want to do something like ( this is
pseudocode ):

function anotherFunction() {
if ( throwAlert ) {
alert(ajaxGetReponse("http://website.com/page?
arguments=longstring"));
} else {
target = document.getElementById("div_id");
div_id.innerHtml = ajaxGetResponse("http://website.com/page?
arguments=longstring");
}

Am I thinking about this the wrong way?
 
K

kouPhax

I'm wanting it to return to whatever script called it -- in other
words, a generic request gateway to server-side data.


Perhaps this is where my understanding of javascript breaks down. If I
can alert() it, and I can divid.innerHtml it, why can't I return it?







Well, I don't want to hard-code the function in the ajaxGetResponse.

In that case, why would I bother to make another function called
ajaxComplete()? Why not just do alert(xmlHttp.responseText); in the
original script?

I am looking to make a generic function that can get some data from
the server-side. I might want to do something like ( this is
pseudocode ):

function anotherFunction() {
if ( throwAlert ) {
alert(ajaxGetReponse("http://website.com/page?
arguments=longstring"));
} else {
target = document.getElementById("div_id");
div_id.innerHtml = ajaxGetResponse("http://website.com/page?
arguments=longstring");

}

Am I thinking about this the wrong way?

Ok perhaps my example was a bit basic. The problem you have here is
that when you do xmlHttp.send(null) your code just carries on it
doesn't wait for something to return (asynchronous). What happens
when the XMLHttpRequest object's state changes (0 through to 4) is
your function that you attached to the onreadystatechange event
property of the xmlHttp object gets triggered (so more than once).
Once the readyState is 4 your alert gets fired. Now if you do a
return from this you aren't returning to anything except the internal
code that triggered the event handler. That is why return is
pointless.

You need to modify your ajaxGetResponse to accept a callback - a
function to execute when you get a response eg,

function ajaxGetResponse(page, callback){
...
...

xmlHttp.onreadystatechange=function() {
if ( xmlHttp.readyState == 4 ) {
callback(xmlHttp.responseText) ;
}
}

...
...
}

And modify your function roughly like this...

function anotherFunction() {
if ( throwAlert ) {
ajaxGetReponse("http://website.com/page?arguments=longstring",
function(t){alert(t)});
} else {
target = document.getElementById("div_id");
ajaxGetResponse("http://website.com/page?arguments=longstring",
function(t){div_id.innerHtml = t});
}

HTH

James
 
L

lawpoop

Ok perhaps my example was a bit basic.  The problem you have here is
that when you do xmlHttp.send(null) your code just carries on it
doesn't wait for something to return (asynchronous).  What happens
when the XMLHttpRequest object's state changes (0 through to 4) is
your function that you attached to the onreadystatechange event
property of the xmlHttp object gets triggered (so more than once).
Once the readyState is 4 your alert gets fired.  Now if you do a
return from this you aren't returning to anything except the internal
code that triggered the event handler.  That is why return is
pointless.

OK, thanks for that. Now I understand. It's an event that happens when
it happens, so basically all I can do is call a function when it does
happen.

That helps tremendously! :)
 
E

Erwin Moller

lawpoop schreef:
I'm wanting it to return to whatever script called it -- in other
words, a generic request gateway to server-side data.


Perhaps this is where my understanding of javascript breaks down. If I
can alert() it, and I can divid.innerHtml it, why can't I return it?

Because of this: xmlHttp.onreadystatechange is called by the browser
when something happens: eg the response from the server is (partially) in.
You don't call that onreadystatechange yourself as a function, do you?
You simply use its existing method onreadystatechange.
Well, I don't want to hard-code the function in the ajaxGetResponse.

In that case, why would I bother to make another function called
ajaxComplete()? Why not just do alert(xmlHttp.responseText); in the
original script?

I am looking to make a generic function that can get some data from
the server-side. I might want to do something like ( this is
pseudocode ):

function anotherFunction() {
if ( throwAlert ) {
alert(ajaxGetReponse("http://website.com/page?
arguments=longstring"));
} else {
target = document.getElementById("div_id");
div_id.innerHtml = ajaxGetResponse("http://website.com/page?
arguments=longstring");
}

Am I thinking about this the wrong way?

I think you approach it in the wrong way.
The problem with:
alert(ajaxGetReponse("http://website.com/page.php");
is that that function ajaxGetReponse should block untill the response is in.
I don't even know how to do that in JavaScript, and I wouldn't want to.

Here is an approach I once used. It is not totally elegant, but gets the
job done.

If you need some 'generic' response mechanism, you could try something
like this:
Make the first line of the response contain the command (you define
yourself), eg:
---------------------
userdetails
name: John Doe
birthday: 12-03-1970
---------------------

or

---------------------
foundcities
New York
Berlin
Amsterdam
---------------------

So when you call your Ajax function ajaxGetReponse(), you also pass that
first line, eg:
ajaxGetReponse("userdetails","http://website.com/userinfo.php?userid=3");

and then in ajaxGetReponse you simply make sure that first argument is
send to the server, and also let the server echo it as its first line in
its response.
So you end up (in this example) with the following URL:
http://website.com/userinfo.php?userid=3&command=userdetails

and userinfo.php will respond always with 'userdetails' as its first line.

When set up like this you can simply use a generic dispatch function
when the Ajax response is in (readyState == 4).

Regards,
Erwin Moller


--
"There are two ways of constructing a software design: One way is to
make it so simple that there are obviously no deficiencies, and the
other way is to make it so complicated that there are no obvious
deficiencies. The first method is far more difficult."
-- C.A.R. Hoare
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,038
Messages
2,570,372
Members
47,018
Latest member
IrisN51866

Latest Threads

Top