Click here to Skip to main content
15,446,510 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Am getting alert error 404 undefined what is the problem with my code

Iservice
C#
public interface IService
{
    [OperationContract]
    [WebInvoke(UriTemplate = "/Welcome/{Name}", Method = "GET", ResponseFormat = WebMessageFormat.Json)]
    string Welcome(string Name);
}


Service
C#
[AspNetCompatibilityRequirements(RequirementsMode
     = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService
    {
        public string Welcome(string Name)
        {
            return "Welcome to Restful Service " + Name;
        }
    }


Web.config
XML
<configuration>

  <system.web>
    <compilation debug="true" targetframework="4.0" />
  </system.web>
  <system.servicemodel>
    <bindings>
      <webhttpbinding>
        <binding name="Bind1" crossdomainscriptaccessenabled="true" />
      </webhttpbinding>

    </bindings>
    <behaviors>
      <endpointbehaviors>
        <behavior name="Endbhvr">
          <webhttp />
        </behavior>
      </endpointbehaviors>
      <servicebehaviors>
        <behavior name="Svrbhvr">
          
          <servicemetadata httpgetenabled="true" />
         
          <servicedebug includeexceptiondetailinfaults="false" />
        </behavior>
      </servicebehaviors>
    </behaviors>
    <servicehostingenvironment aspnetcompatibilityenabled="false" multiplesitebindingsenabled="true" />
    <services>
      <service name="WcfService2.Service1" behaviorconfiguration="Svrbhvr">
        <endpoint address="" binding="webHttpBinding"
  behaviorConfiguration="Endbhvr" contract="WcfService2.IService" bindingConfiguration="Bind1">
        </endpoint>
        <endpoint
          address="mex"
          binding="mexHttpBinding"
          contract="IMetadataExchange"/>
      </endpoint>
</service>
     
    </services>
  </system.servicemodel>
  <system.webserver>
    <modules runallmanagedmodulesforallrequests="true" />
   
    <directorybrowse enabled="true" />
  </system.webserver>

</configuration>


Asp code
ASP.NET
<script src="Scripts/jquery-2.0.3.js"></script>
    <script type="text/javascript" lang="javascript">
        function ajaxcall() {
            $.ajax({
                url: "http://localhost:50848/Service1.svc/Welcome/mahesh?calback=?",
                type: "GET",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: {},
                processdata: true,
                success: function (response) {
                    var data = response;
                    alert(data);
                },

                error: function (e) {
                    alert('error ' + e.status + ' ' + e.responseText);

                }
            });
        }
        $().ready(function () {
            $('#Button1').click(ajaxcall);
        })
</script>
</head>

<body>
    <form id="form1"  runat="server">
    <div>
     <button id="Button1" >Click Me</button>
    </div>
    </form>
</body>
Posted
v5
Comments
IpsitaMishra 30-Oct-13 6:28am    
Is it calling the service or not ?
karthik mushyam 30-Oct-13 6:29am    
not calling its getting alert error 404 undefined
[no name] 30-Oct-13 8:12am    
404 signifies file not found error...Check your Rest Services's URL that you are passing to Ajax Call..
[no name] 30-Oct-13 8:14am     CRLF
And How are you passing no parameters to your function data: {} whereas your function expects a parameter Welcome(string Name)
[no name] 1-Nov-13 4:32am     CRLF
Just try this... Wheer instead of URL Link, give a path from machine & have a "Json" File, which can atleast confirm, is that part is working fine. THis part of code will pop up alert the content in that Jason File in the Folder [rest-> File name Bhuvan] <script type="text/javascript" language="javascript"> function ajaxcall() { $.ajax({ url: "/rest/Bhuvan", type:"GET", contentType: 'application/json; charset=utf-8', dataType: "json", success: function (Bhuvan) { var data = Bhuvan; alert(data); }, error: function (e) { alert('error ' + e.status + ' ' + e.responseText); }, }); } </Script>

Here You have defined one parameter in your template url & method in service Contract.
C#
public interface IService
{
    [OperationContract]
    [WebInvoke(UriTemplate = "/Welcome/{Name}", Method = "GET", ResponseFormat = WebMessageFormat.Json)]
    string Welcome(string Name);
}

First Check Your JavaScript function is being called or not.
You are not passing any parameter in your ajax call.
And Your Ajax call should be like this...
JavaScript
var YourData = "/&Hello";

//You should use jsonp with EXPLICIT CALLBACK Function
            $.ajax({
                type: "GET",
                contentType: "application/json;charset=utf-8",
                url: 'http://localhost:49485/WCFRestService.svc/SayHelloWorld?callback=?' + YourData,
                dataType: "jsonp",
                jsonpCallback: "MyCallBack",
                success: MyCallBack,
                error: function () {
                    alert("error");
                }
            });

        //We call this Function form success: explicitlly
        function MyCallBack(data) {
            alert('success : ' + data);
        }


And Your Responce data should be wrapped like MyCallback({YourjsonData}).
In Your WCF service write your Responce like this.
C#
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = "application/json";
string callback = HttpContext.Current.Request.QueryString["callback"];
HttpContext.Current.Response.Write(callback + "( " + new JavaScriptSerializer().Serialize(YourListObjectGoesHere)  + " )");
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();


Hope This Helps You.
------------------------
Pratik Bhuva.
 
Share this answer
 
v2
Hi,

Step 1: Please see use this in your web config file.

Step 2: Test the service directly in Browser using below URL.


Step 1: Web Config File Code.
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WcfService2.Service1" behaviorConfiguration ="MyServiceBehaviour">
        <endpoint address =""
                  binding="webHttpBinding"
                  contract="WcfService2.IService1"
                  behaviorConfiguration="MyEndpointBehavior" />
      </service>
    </services>
    
    
    <behaviors>
    
      <serviceBehaviors>
        <behavior name="MyServiceBehaviour">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    
      <endpointBehaviors>
        <behavior name="MyEndpointBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    
    </behaviors>
    
    
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  
</configuration>


Step 2: Test URL
Use thr proper Localhost:portNumber [First Run your Service then at last add /Welcome/Bhuvan ] , now your Jason File will be Downloading.

The Code which you shown up has the problem where the service cannot invoke method.
http://localhost:57832/Service1.svc/Welcome/Bhuvan
 
Share this answer
 
v2
Hi,

Please check for the JQuery Libarary are added in the Scripts Folder you mentioned in the code.
<script src="Scripts/jquery-2.0.3.js"></script>


Please check for the Proper Method = "GET/POST" for WebInvoke and try the same.

[WebInvoke(UriTemplate = "/Welcome/{Name}", Method = "GET", ResponseFormat = WebMessageFormat.Json)]



Try This in Script File of Webpage.

 <script type="text/javascript" language="javascript">
        function ajaxcall() {
            $.ajax({
                url: "/rest/Bhuvan",
                type:"GET",
                contentType: 'application/json; charset=utf-8',
                dataType: "json",
                success: function (Bhuvan) {
                    var data = Bhuvan;
                    alert(data);
                },

                error: function (e) {
                    alert('error ' + e.status + ' ' + e.responseText);

                },
            });
        }
</Script>


Thanks!
 
Share this answer
 
v2
Comments
karthik mushyam 1-Nov-13 3:21am    
Thanks All Code project people ...for giving a lot of information on my question

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900