www.webdeveloper.com
Results 1 to 2 of 2

Thread: Directly returning a value through ajax

  1. #1
    Join Date
    Oct 2009
    Posts
    69

    Question Directly returning a value through ajax

    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?

  2. #2
    Join Date
    Oct 2009
    Posts
    69

    resolved

    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;
    	}
    }

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles