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:
Code:
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?
Found the solution afterwords. For anyone interested, I reworked the code like this:
Code:
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;
}
}
Bookmarks