XMLHttpRequest POST request to ASP Web Service - whats wrong?

Discussion in 'JavaScript' started by Raizern, Dec 3, 2008.

  1. #1
    Have a Web Service Method (asmx) that basically looks like this
    
        [WebMethod]
        public string Hello(string p)
        {
            return "Result:"+p;
        }
    
    Code (markup):
    Now want to call it via this page

    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title>Sandbox Page</title>
        <script language="javascript"  type="text/javascript">
            function init() {
                var divPlacer = document.getElementById("divPlacer");
                var divButton = document.createElement("input");
                divButton.type = "button";
                divButton.value = "Go";
                divButton.onclick = testRequest;
                
                divPlacer.appendChild(divButton);
            }
            
    	    function testRequest()
    	    {
                var httpRequest = new XMLHttpRequest();
    		    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    		    httpRequest.open('POST', 'http://localhost/WebServ2/Service.asmx/Hello', true);
    		    httpRequest.onreadystatechange = function()
    		    {
    			    if(httpRequest.readyState == 4)
    			    {
    				    document.getElementById("response").innerHTML = httpRequest.responseText;
    			    }
    		    }
    		    httpRequest.send('p=2');
    	    }
        </script>
    </head>
    <body onload="init();">
        <div id="response">Response goes here</div>
        <br />
        <div id="divPlacer"></div>
        
        <form target="_blank" action='http://localhost/WebServ2/Service.asmx/Hello' method="POST"> 
        Type Anything here: <input type="text" size="30" name="p"/><input type="submit" value="Submit" class="button"/>
        </form>
    
    </body>
    </html>
    
    Code (markup):
    Now when i click on the Submit button ... I'd get the desired result (simply saying the web service method works fine)

    However if I try to use the Javascript code to call the web service method ... I get an "uncaught exception" in FFs Firebug and an "unspecified error" in IE.

    Can anyone tell me whats wrong here or if I'm missing something? thanks :)
     
    Raizern, Dec 3, 2008 IP
  2. MMJ

    MMJ Guest

    Messages:
    460
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #2
    1. You should be using the relative, not absolute URI. Cross-site ajax is a whole different story.
    2. You should be check for the activex ajax control, even for IE7.
     
    MMJ, Dec 3, 2008 IP