www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: Function not returning value

  1. #1
    Join Date
    Jan 2009
    Posts
    53

    Question Function not returning value

    The following code is supposed to return a variable containing text, currently the code posts the data but returns an "undefined" variable. Can someone tell me what's wrong? Thanks.

    Code:
    function ajaxPost(params, url){
    	
    	var XMLHttpRequestObj = false;
    		
    	if (window.XMLHttpRequest){
    		XMLHttpRequestObj = new XMLHttpRequest();
    	} else if (window.ActiveXObject){
    		XMLHttpRequestObj = new ActiveXObject("Microsoft.XMLHttp");
    	}
    		
    	if (XMLHttpRequestObj){
    		XMLHttpRequestObj.open("POST", url, true);
    		XMLHttpRequestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    		XMLHttpRequestObj.setRequestHeader("Content-length", params.length);
    		XMLHttpRequestObj.setRequestHeader("Connection", "close");
    		
    		XMLHttpRequestObj.onreadystatechange = function(){
    			if (XMLHttpRequestObj.readyState == 4 && XMLHttpRequestObj.status == 200){
    				var requestResponse = XMLHttpRequestObj.responseText;
    				delete XMLHttpRequestObj;
    				return (requestResponse);				
    			}
    		}
    		XMLHttpRequestObj.send(params);
    	}
    }
    The returned value is alerted - currently shows "AJAX: undefined"
    Code:
    ...
    ...
            var ajaxResponse = ajaxPost(params, url);
    	alert("AJAX: " + ajaxResponse);

  2. #2
    Join Date
    Jun 2007
    Posts
    667
    Quote Originally Posted by Dan0 View Post
    The following code is supposed to return a variable containing text, currently the code posts the data but returns an "undefined" variable. Can someone tell me what's wrong? Thanks.
    ajaxPost returns nothing. The readystatechange handler captures the response text (after ajaxPost has terminated) but you're not saving it anywhere.

  3. #3
    Join Date
    Jan 2009
    Posts
    53
    Quote Originally Posted by Sterling Isfine View Post
    ajaxPost returns nothing. The readystatechange handler captures the response text (after ajaxPost has terminated) but you're not saving it anywhere.
    I don't follow; what do you mean I'm not saving it anywhere? What about the lines:
    Code:
    var requestResponse = XMLHttpRequestObj.responseText;
    delete XMLHttpRequestObj;
    return (requestResponse);
    Isn't the response stored in "requestResponse" and then returned, exiting the function?

  4. #4
    Join Date
    Mar 2009
    Location
    Wherever i lay my hat
    Posts
    180
    you are returning from the anonymous function:

    Code:
    XMLHttpRequestObj.onreadystatechange = function(){
      if (XMLHttpRequestObj.readyState == 4 && XMLHttpRequestObj.status == 200){
        var requestResponse = XMLHttpRequestObj.responseText;
        delete XMLHttpRequestObj;
        return (requestResponse);				
    }
    if you want to return a value from ajaxPost() you need to declare a variable outside the anonymous function and then set its value inside it:
    Code:
    function ajaxPost(params, url){
    	
    	var XMLHttpRequestObj = false, requestResponse;
    		
    	if (window.XMLHttpRequest){
    		XMLHttpRequestObj = new XMLHttpRequest();
    	} else if (window.ActiveXObject){
    		XMLHttpRequestObj = new ActiveXObject("Microsoft.XMLHttp");
    	}
    		
    	if (XMLHttpRequestObj){
    		XMLHttpRequestObj.open("POST", url, true);
    		XMLHttpRequestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    		XMLHttpRequestObj.setRequestHeader("Content-length", params.length);
    		XMLHttpRequestObj.setRequestHeader("Connection", "close");
    		
    		XMLHttpRequestObj.onreadystatechange = function(){
    			if (XMLHttpRequestObj.readyState == 4 && XMLHttpRequestObj.status == 200){
    				requestResponse = XMLHttpRequestObj.responseText;
    				delete XMLHttpRequestObj;		
    			}
    		}
    		XMLHttpRequestObj.send(params);
    		return (requestResponse);		
    	}
    }

  5. #5
    Join Date
    Jan 2009
    Posts
    53
    Thanks for the explanation; I completely overlooked the fact that the XMLHttpRequestObj.responseText was inside an anonymous function. Unfortunatley, however, even after making the suggested changes the code still returns "undefined." Any ideas why? Currently the ajaxPost() code is:

    Code:
    function ajaxPost(params, url){
    	
    	var XMLHttpRequestObj = false;
            var requestResponse;
    		
    	if (window.XMLHttpRequest){
    		XMLHttpRequestObj = new XMLHttpRequest();
    	} else if (window.ActiveXObject){
    		XMLHttpRequestObj = new ActiveXObject("Microsoft.XMLHttp");
    	}
    		
    	if (XMLHttpRequestObj){
    		XMLHttpRequestObj.open("POST", url, true);
    		XMLHttpRequestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    		XMLHttpRequestObj.setRequestHeader("Content-length", params.length);
    		XMLHttpRequestObj.setRequestHeader("Connection", "close");
    		
    		XMLHttpRequestObj.onreadystatechange = function(){
    			if (XMLHttpRequestObj.readyState == 4 && XMLHttpRequestObj.status == 200){
    				requestResponse = XMLHttpRequestObj.responseText;
    				delete XMLHttpRequestObj;		
    			}
    		}
    		XMLHttpRequestObj.send(params);
    		return (requestResponse);		
    	}
    }
    The receiving function's code is:
    Code:
    window.onload = function(){
    	$(".error").hide();
    	if (document.getElementById("featureForm")){
    		document.getElementById("featureForm").onsubmit = featureDetails;
    	}
    }; // end onload function
    
    function featureDetails(){
    	...
    	...
    	...	
    	var params = "type=featureDetails" + "&featureTitle=" + featureTitle + "&featureLocation=" + featureLocation + "&featTimePeriod=" + featTimePeriod + "&featureCost=" + featureCost + "&featDescription=" + featDescription;
    	
    	var url = "feature_cases.php";
    	
    	var ajaxResponse = ajaxPost(params, url);
    	alert("AJAX: " + ajaxResponse);
    	return false;
    }

  6. #6
    Join Date
    Mar 2009
    Location
    Wherever i lay my hat
    Posts
    180
    edit: ZeroKilled (1 post lower) is right. i overlooked that. ajaxPost() has returned a "long time" ago, when the onreadystatechange callback function is called.
    Last edited by haulin; 03-27-2009 at 02:12 PM.

  7. #7
    Join Date
    May 2006
    Location
    Odenton, MD
    Posts
    1,449
    try setting the request to sync (false in open method). because the request is async, ajaxPost return undefined due that async allow script to continue execution without waiting request to do it's part. so, in sync request script have to wait until the request is done after sending (send method) the request.

  8. #8
    Join Date
    Jan 2009
    Posts
    53
    I tried setting the post to sync (false) but that didn't work either. I'm thoroughly confused as to what the problem is. Below is a slightly different version of the code that works fine. The only difference is the code below sends the responseText as an argument, rather than returning it.

    Code:
    XMLHttpRequestObj.onreadystatechange = function(){
    			if (XMLHttpRequestObj.readyState == 4 && XMLHttpRequestObj.status == 200){
    				callback(XMLHttpRequestObj.responseText);
    				delete XMLHttpRequestObj;
    			} 
    		}
    If you want I can post the server-side script (PHP), but as I mentioned before the ajax code does post the data to the script, which then processes the data.

  9. #9
    Join Date
    May 2006
    Location
    Odenton, MD
    Posts
    1,449
    using haulin code, this is what i tried and worked correctly to me.
    Code:
    function ajaxPost(params, url){
    var XMLHttpRequestObj = false, requestResponse;
    	if (window.XMLHttpRequest){
    	XMLHttpRequestObj = new XMLHttpRequest();
    	} else if (window.ActiveXObject){
    	XMLHttpRequestObj = new ActiveXObject("Microsoft.XMLHttp");
    	}
    	
    	if (XMLHttpRequestObj){
    	XMLHttpRequestObj.open("POST", url, false);
    	XMLHttpRequestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    	XMLHttpRequestObj.setRequestHeader("Content-length", params.length);
    	XMLHttpRequestObj.setRequestHeader("Connection", "close");
    	XMLHttpRequestObj.onreadystatechange = function(){
    		if (XMLHttpRequestObj.readyState == 4 && XMLHttpRequestObj.status == 200){
    		requestResponse = XMLHttpRequestObj.responseText;
    		delete XMLHttpRequestObj;		
    		}
    	}
    	XMLHttpRequestObj.send(params);
    	return requestResponse;
    	}
    }
    because i tried it local, i had removed/modified some statements, like doing GET request, removing request headers, not to check the status, and send(null). it worked to me.

  10. #10
    Join Date
    Mar 2009
    Location
    Wherever i lay my hat
    Posts
    180
    yup. for me, too. i tried it on localhost exactly as it is in last ZeroKilled's post and it returned the desired text.

    besides, if you are going synchronous, you don't need any callback function to check the readystatechange event. this worked for me as well:

    Code:
    function ajaxPost(params, url) {
      var XMLHttpRequestObj = false;
      if (window.XMLHttpRequest) {
        XMLHttpRequestObj = new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        XMLHttpRequestObj = new ActiveXObject("Microsoft.XMLHttp");
      }
      if (XMLHttpRequestObj) {
        XMLHttpRequestObj.open("POST", url, false);
        XMLHttpRequestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        XMLHttpRequestObj.setRequestHeader("Content-length", params.length);
        XMLHttpRequestObj.setRequestHeader("Connection", "close");
        XMLHttpRequestObj.send(params);
        return XMLHttpRequestObj.responseText;
      }
    }
    Last edited by haulin; 03-27-2009 at 05:16 PM.

  11. #11
    Join Date
    Jan 2009
    Posts
    53
    I got the synchronous code to work once I took out the onreadystatechange event callback.

    Interestingly enough, I also got an asynchronous code to work, however, only when I'm debugging it in firebug. Anyone know why it only works while debugging? Here's the code I used:

    Code:
    var AjaxPost = {
    	post: function(params, url){
    		var XMLHttpRequestObj = false;
    		
    		if (window.XMLHttpRequest){
    			XMLHttpRequestObj = new XMLHttpRequest();
    		} else if (window.ActiveXObject){
    			XMLHttpRequestObj = new ActiveXObject("Microsoft.XMLHttp");
    		}
    			
    		if (XMLHttpRequestObj){
    			XMLHttpRequestObj.open("POST", url, true);
    			XMLHttpRequestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    			XMLHttpRequestObj.setRequestHeader("Content-length", params.length);
    			XMLHttpRequestObj.setRequestHeader("Connection", "close")
    			XMLHttpRequestObj.send(params);
    		}
    		this.requestResponse = XMLHttpRequestObj.responseText;
    		delete XMLHttpRequestObj;
    	},
    	requestResponse: null
    };
    
    ...
    ...
    AjaxPost.post(params, url);
    alert(AjaxPost.requestResponse);

  12. #12
    Join Date
    Jun 2007
    Posts
    667
    Quote Originally Posted by Dan0 View Post
    Code:
    AjaxPost.post(params, url);
    alert(AjaxPost.requestResponse);
    Probably because as you step the instructions one by one, there's time for the request to complete before you alert the result.
    I suspect that you still haven't grasped this concept entirely.

  13. #13
    Join Date
    Jan 2009
    Posts
    53
    Quote Originally Posted by Sterling Isfine View Post
    I suspect that you still haven't grasped this concept entirely.
    That very well maybe the case. What I understand, and correct me if I'm wrong, is that my code sends a request and then moves on. As it is asynchronous it doesn't wait for a reply - thus moving on to the "alert" code in spite of there being nothing to alert. With that said I don't understand why I can't assign a function to the onreadystatechange that when the readystate is 4 and status is 200 calls a method that alerts the response as in the code below:

    Code:
    var Ajax = {
    	post : function(params, url){
    		var XMLHttpRequestObj = false;
    		
    		if (window.XMLHttpRequest){
    			XMLHttpRequestObj = new XMLHttpRequest();
    		} else if (window.ActiveXObject){
    			XMLHttpRequestObj = new ActiveXObject("Microsoft.XMLHttp");
    		}
    			
    		if (XMLHttpRequestObj){
    			XMLHttpRequestObj.open("POST", url, true);
    			XMLHttpRequestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    			XMLHttpRequestObj.setRequestHeader("Content-length", params.length);
    			XMLHttpRequestObj.setRequestHeader("Connection", "close");
    			XMLHttpRequestObj.send(params);
    			
    			XMLHttpRequestObj.onreadystatechange = function(){
    				if (XMLHttpRequestObj.readyState == 4 && XMLHttpRequestObj.status == 200){
    					this.saveResponse(XMLHttpRequestObj.responseText);
    					delete XMLHttpRequestObj;
    				} 
    			}
    		}
    	},
    	saveResponse : function(response){
    		alert(response);
    	}
    };
    Last edited by Dan0; 03-28-2009 at 05:26 PM.

  14. #14
    Join Date
    May 2006
    Location
    Odenton, MD
    Posts
    1,449
    Code:
    this.saveResponse(XMLHttpRequestObj.responseText);
    this refer to the object that contain the event onreadystatechange, not the Ajax object. so, it refer to the object XMLHttpRequestObj, but saveResponse isn't a method of such object. you will need to use the full notation object:

    Code:
    XMLHttpRequestObj.onreadystatechange = function(){
    				if (XMLHttpRequestObj.readyState == 4 && XMLHttpRequestObj.status == 200){
    					Ajax.saveResponse(XMLHttpRequestObj.responseText);
    					delete XMLHttpRequestObj;
    				} 
    			}

  15. #15
    Join Date
    Mar 2009
    Location
    Wherever i lay my hat
    Posts
    180
    or the very popular workaround:

    Code:
    var Ajax = {
    	post : function(params, url){
    		var XMLHttpRequestObj = false, that = this;
    		
    		if (window.XMLHttpRequest){
    			XMLHttpRequestObj = new XMLHttpRequest();
    		} else if (window.ActiveXObject){
    			XMLHttpRequestObj = new ActiveXObject("Microsoft.XMLHttp");
    		}
    			
    		if (XMLHttpRequestObj){
    			XMLHttpRequestObj.open("POST", url, true);
    			XMLHttpRequestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    			XMLHttpRequestObj.setRequestHeader("Content-length", params.length);
    			XMLHttpRequestObj.setRequestHeader("Connection", "close");
    			XMLHttpRequestObj.send(params);
    			
    			XMLHttpRequestObj.onreadystatechange = function(){
    				if (XMLHttpRequestObj.readyState == 4 && XMLHttpRequestObj.status == 200){
    					that.saveResponse(XMLHttpRequestObj.responseText);
    					delete XMLHttpRequestObj;
    				} 
    			}
    		}
    	},
    	saveResponse : function(response){
    		alert(response);
    	}
    };

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