views:

263

answers:

1

Hi guys,

I wanted to know it is possible to call a hosted .net web service from a HTML page using jQuery? I tried this piece of code, but it doesn't work for me:

 $('#myForm').click(function() {
        $.ajax({
            type: "POST",
            data: '{}',
            url: "http://localhost:49590/Service.asmx?op=HelloWorld",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success:
                function(response) {                   
                    alert(response.d);
                },
            failure:
                function(result) {
                    alert(result.status + ' ' + result.statusText);
                }
        });
    });

And the webservice is as such:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }
}

I have searched for this and found only examples where it is done from asp.net or asp.net mvc projects. I am not sure what I am missing but I thought this was possible from a plain HTML site with javascript, so can someone please point me in the right direction.

Cheers!

+3  A: 

I think you just have some syntax errors. I created the following classic web service:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class HelloWorld : System.Web.Services.WebService
{
    [WebMethod]
    public string Hello(string name)
    {
        return "Hello " + name;
    }
}

And the following HTML page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
    <title>Calling Classic Web Services with jQuery</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
    <script type="text/javascript">
      $(document).ready(function () {
        $("a#SayHello").click(function (e) {
          e.preventDefault();

          $.ajax({
            type: 'POST',
            data: '{"name": "' + $("input#name").val() + '"}',
            url: 'http://localhost:7663/HelloWorld.asmx/Hello',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success:
              function (data, textStatus, XMLHttpRequest) {
                alert(data.d);
              },
            error:
              function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
              }
          });
        });
      });    
    </script>
</head>
<body>
  <input id="name" /><a id="SayHello" href="#">Greetings!</a>  
</body>
</html>

And was able to produce a valid response.

Hope that helps!

EDIT: Here is how I created the web service in Visual Studio 2010. Note that I changed my framework to 3.5, though 2.0 and 3.0 offer the same project. 4 does not.

Classic Web Service in Visual Studio 2010

The web config might look a little bare if you're not using VS2010, but know I didn't touch it at all:

<?xml version="1.0"?>
<configuration>
<configSections>
    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
            <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
                <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/></sectionGroup></sectionGroup></sectionGroup></configSections><appSettings/>
<connectionStrings/>
<system.web>
    <compilation debug="true">
        <assemblies>
            <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation>
    <!--
  The <authentication> section enables configuration 
  of the security authentication mode used by 
  ASP.NET to identify an incoming user. 
-->
    <authentication mode="Windows"/>
    <!--
   The <customErrors> section enables configuration 
   of what to do if/when an unhandled error occurs 
   during the execution of a request. Specifically, 
   it enables developers to configure html error pages 
   to be displayed in place of a error stack trace.

   <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
     <error statusCode="403" redirect="NoAccess.htm" />
     <error statusCode="404" redirect="FileNotFound.htm" />
   </customErrors>
-->
    <pages>
        <controls>
            <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></controls></pages>
    <httpHandlers>
        <remove verb="*" path="*.asmx"/>
        <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></httpHandlers>
    <httpModules>
        <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></httpModules></system.web>
<system.codedom>
        <compilers>
            <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
                <providerOption name="CompilerVersion" value="v3.5"/>
                <providerOption name="WarnAsError" value="false"/></compiler></compilers></system.codedom>
<system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
    <modules>
        <remove name="ScriptModule"/>
        <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></modules>
    <handlers>
        <remove name="WebServiceHandlerFactory-Integrated"/>
        <remove name="ScriptHandlerFactory"/>
        <remove name="ScriptHandlerFactoryAppServices"/>
        <remove name="ScriptResource"/>
        <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></handlers></system.webServer>
<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1" appliesTo="v2.0.50727">
        <dependentAssembly>
            <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
            <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/></dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
            <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/></dependentAssembly></assemblyBinding></runtime></configuration>
Jason Alati
I tried your code, but I am getting data is null on the return.
pwee167
Can you please show me what the web.config looks like? I added a WCF project then removed the default service and added a plain web service. Is this what you did?
pwee167
I added a picture and the web.config. We're not dealing with a WCF service, rather a classic ASMX web service. If you'd rather create a WCF service and call it using AJAX, that too is possible but if you don't need all of the flexibility of WCF, ASMX is fine.
Jason Alati
Thanks for all that. I really appreciate it. I did as you told (and I am using VS2010). It's returning back with a textStatus of "Success", but I am getting null for the data.d.
pwee167
I'd recommend downloading Fiddler2 (or the HTTP traffic analyzer of your choice -- Firebug will even suffice) and looking at both the request and response. Make sure the request is getting there in entirety.
Jason Alati
Cheers will do.
pwee167
I got this finally working, but only when I had the html page inside the webservice project. As soon as I took it out of the project, it did not work. No idea why this is the case.
pwee167