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); } } Code (markup): 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?
These code samples don't do what I'm looking to do. I don't want to change the innerHTML from within the body of a function. I simply want the functions to return a value. That way I could place a block of code inside a div tag like this: <div id='output'> <script>document.write(print_output());</script> </div> rather than putting a statement inside the ajax function itself like: document.getElementById('output').innerHTML = "output";
Okay, found something that works. 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; } } Code (markup):