PDA

View Full Version : Directly returning a value through ajax


bonecone
12-01-2009, 10:19 PM
I'm attempting to simplify my javascript code when it comes to ajax, but afterwords it only prints 'undefined' to the screen rather than what I want it to print.

I want to be able to put something like this on my main page
onclick="document.getElementById('output').innerHTML = print_output();"
where print_output() is the ajax function. This way I don't have to use a function to assign values directly to innerHTML and I don't have to muck about with a js file whenever I want to change my page layout.

To do this, I created a recursive function:

function print_output(return_value) {

// if a value has been passed to the function, simply return it
if(return_value || return_value == 0) {
return return_value;
}

// otherwise call the response object
else {
http = getHTTPObject();

// recursively calls the first function once the
// text has been received
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
print_output(http.responseText);
}
}

url = "index.php";
params = "output=Ajax is working properly";

http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(params);
}
}


but like I said, it prints 'undefined' out to the screen. Why isn't this printing the contents that it receives from 'index.php' like it's supposed to?

rnd me
12-02-2009, 12:11 AM
to use it with the inline syntax you posted, it must be sync:




function print_output(return_value) {

// if a value has been passed to the function, simply return it
if(return_value || return_value == 0) {
return return_value;
}

// otherwise call the response object
else {
http = getHTTPObject();

url = "index.php";
params = "output=Ajax is working properly";

http.open("POST", url, false);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(params);
return http.responseText;
}
}

or, you could pass the destination in the inline call:


so inline would be:
onclick="print_output('output');"



function print_output(dest) {
http = getHTTPObject();

url = "index.php";
params = "output=Ajax is working properly";

http.open("POST", url, true);

http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById(dest).innerHTML = http.responseText;
}
}

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(params);

}

bonecone
12-02-2009, 12:37 AM
That works perfect! Thanks!