none
wcf invoking using Javascript

    Question

  • dear squad,

    I am trying to consuming the Wcf service using javascript with html and also how to bind the database fields (retrieved  from the WCF service) into html controls.

    please could you provide to me link and share to me any related examples.

    Thanks in advance,


    nareshrajuu

    Friday, August 03, 2012 4:47 AM

Answers

  • Your URI template need to be plain string

    Change this [WebGet(UriTemplate = "/getname()")]

    To

    [WebGet(UriTemplate = "/getname")]

    BTW when you dont have any elements to pass to the method you need to use GET and not POST.

    I recommend you run the solution i sent and test first. and start integrating your code in to the same.

    .reg file you have to use it to register JSON MIME type reply for the browser. Just unzip it and double click on it. it registers the MIME type for you.



    Please mark the replies as Answered if they help and Vote if you found them helpful.

    Tuesday, August 07, 2012 5:04 AM

All replies

  • Hi,

    The best way to code your WCF to make it client enabled is through REST. so that you can use JSON to play fully with javascript, Jquery. It gives lot of performance for your UI.

    Here is the code proejct article helps you to get some idea.

    Hope it helps. If you have any more specific questions let me know



    Please mark the replies as Answered if they help and Vote if you found them helpful.

    Friday, August 03, 2012 5:18 AM
  • Hi veerendra Kumar,

    Yes, I saw above aritical.

    but before that i moved one more step 

    here 

    my html :

    <html>

    <head>Getting wcf data</head>

    <script type="text/javascript" src="jquery-1.7.2.min.js"></script>

    <script>

    function Button1_onclick() 

       {                       
                var pid = TextArea2.innerHTML;
                $.support.cors = true;

          $.ajax({
                    type: "GET",
                    url:"http://localhost:8888/Service1.svc/getempdetails",
                      data : JSON.stringify({ eid: eid}),
                    contentType :"application/json",
                    dataType : "xml/json",
                    ProcessData: false,
                    error: function (XmlHttpRequest, status, error) { alert('Error from Ajax Method: ' + error); },
                    success: function (msg)
                        {
                            var theRealData = msg.d;
                            document.getElementById("welcomeMsg").innerHTML +=  theRealData;
                        }
                  });
        }

    </script>

    <body>

    <textarea id="TextArea2" name="S2" rows="2"></textarea>&nbsp;<br />
    &nbsp;<input id="BtnPatient" type="button" value="Submit" 
                onclick="javascript:Button1_onclick()" /><br />
        </body>

    </html>

    when i was executing this :

    getting an error as  "Bad request"

    this error getting  from here "  error: function (XmlHttpRequest, status, error) { alert('Error from Ajax Method: ' + error); },"

    please let me know where i did mistake.

    i am sure there is no issues in WCF service.

    Thanks in Advance


    nareshrajuu

    Friday, August 03, 2012 5:50 AM
  • I believe there is something wrong with URI template you are using.

    Can you please post you service implementation along with Interface and service config?



    Please mark the replies as Answered if they help and Vote if you found them helpful.

    Friday, August 03, 2012 6:38 AM
  • Yes Veerandra Kumar,

    i am posting all my service  with the source code also

    please see here:

    IService1:cs

          

    [ServiceContract]
        public interface IService1
        {
            [OperationContract]
            [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
            [WebGet(UriTemplate = "/getname", ResponseFormat = WebMessageFormat.Xml)]
            string GetData();

            [OperationContract]
            [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]    
            CompositeType GetDataUsingDataContract(CompositeType composite);

            [OperationContract]
            [WebInvoke(Method = "GET",BodyStyle = WebMessageBodyStyle.Wrapped,ResponseFormat = WebMessageFormat.Json)]
            [WebGet(UriTemplate="/getname",ResponseFormat=WebMessageFormat.Xml)]
            string getname();

            [OperationContract]
            [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
         
            [OperationContract]
                  [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat                    = WebMessageFormat.Json)]
            List<EmployeeInformation> getempdetails(int eid);

        }                           

    Service1.svc.cs

           

    public List<EmployeeInformation>  getempdetails(int eid)

     DataClasses1DataContext datacontxt = new DataClasses1DataContext();

            {
                var res = from p in datacontxt.EmployeeInformations where p.EID == eid select p;
                return res.ToList();
            }

    Note :here i used LINQ to SQL  for database connection so no issues.

    please let me know where i did mistake.


    nareshrajuu

    Friday, August 03, 2012 6:58 AM
  • i believe you need to specifiy the URL template for your getempdetails method.


    Please mark the replies as Answered if they help and Vote if you found them helpful.

    Friday, August 03, 2012 7:07 AM
  • i added after that No luck!

    please see here:

     [OperationContract]
                  [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat                    = WebMessageFormat.Json)]

     [WebGet(UriTemplate = "/getempdetails", ResponseFormat = WebMessageFormat.Json)]
            List<EmployeeInformation> getempdetails(int eid);;

    Note :

    This is not Restful WCF service and also i am doing for phonegap with windows phone.


    nareshrajuu

    Friday, August 03, 2012 7:27 AM
  • try this

    [WebInvoke(Method = "GET", 
                        ResponseFormat = WebMessageFormat.Json, 
                        UriTemplate = "getempdetails/{id}")]
    
    change id datatype to string and convert it to int with in the method.


    Please mark the replies as Answered if they help and Vote if you found them helpful.

    Friday, August 03, 2012 8:07 AM
  • Try it from browser first and make sure that you are getting response.

    like http://yourservice/service.svc/getempdetails/10 (10 could be id you may want to pass).



    Please mark the replies as Answered if they help and Vote if you found them helpful.

    Friday, August 03, 2012 8:10 AM
  • Thank u somuch for your reply,

    here i am passing empid through the textbox. then click on button it will take the textboxtext as input then execute the my iteration. for that i provided html code also above

    here when i was click on the submit button.then it will displays the associated employee details. for that i am using above code.

    please let me know the how to achieve the issue. 

    Thanks in advance


    nareshrajuu

    Friday, August 03, 2012 8:48 AM
  • Hi,

    As i mentioned in the previous post, first you need to define the URI template with parameter. and make sure that that the REST URI is working properly from browser itself.

    For example your service is: http://localhost:8888/Service1.svc/

    Method is: getempdetails

    Parameter is: id

    Your URI template for the getempdetails method is

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

    Now open browser and type the below URL

     http://localhost:8888/Service1.svc/getempdetails/id (where id is the id you want to pass)

    This will give you the output if your service method works properly. Then you can use your ajax code

    Make sure that you are passing the id properly while calling the WCF. Your call for passing id is something like below

    data : JSON.stringify({ eid: eid}),

    i dont see you are passing employ id here.

    I believe you are not sendign the id in this call it should be something like this

    var employid = <get employid from text box>

    var input = { "eid" : employid };

    $.ajax({  

    data : JSON.stringify(input),

       ...
    });

    Make sure that you service config is properly defined.

    Before testing from your client, i recommend test it directly using URL as it is rest based.

    Hope this explanation is detailed enough to resolve your problem :-).



    Please mark the replies as Answered if they help and Vote if you found them helpful.

    Friday, August 03, 2012 10:29 AM
  • Thanks for your reply,

    what ever u said that's i did but no luck.

    wcf service working in WcfTestClient ,but where as browser showing above error,and also did n't work properly at least one method ,showing for all method in wcf service "Bad Request error".

    this same service consumed in C# application it's worked fine. so may be not service problem.

    i think may be  some other problem in browser or javascript .

    i am using browser as IE 9.

    please give to me any suggestion 


    nareshrajuu

    Friday, August 03, 2012 10:52 AM
  • Do you mind sending the zip of solution file to my mail id? (If it's not IP!) I would take a look at that and get back to you. (bveerendrakumar@hotmail.com)


    Please mark the replies as Answered if they help and Vote if you found them helpful.


    Friday, August 03, 2012 11:00 AM
  • Thank you so much for lot of your effort,

    if you don't mind could you see the below links

    note 

    1) some persons discussed about problem in IIS

    2)wcf  SOAP envelop Problem.

    3)and also Browser Effect.

    http://stackoverflow.com/questions/8611453/http-400-bad-request-error-with-wcf-service-when-message-size-exceeds-64k

    http://stackoverflow.com/questions/11139799/i-am-almost-there-phonegap-android-connect-to-wcf-service


    nareshrajuu

    Friday, August 03, 2012 11:14 AM
  • It might impact you if you are sending long message size that exceeds 64 K. i believe getting on employ details may not be that big. However you can increase the outgoing message size in WCF service.

    I still feel it's not related to any of these issues. When you are getting response from other application, it should work everwhere unless you make some mistake in the way you are consuming the service.

    I have tried a sample in my machine with your scenario, everything works seamlessly without any issue. not sure why its not working for you.



    Please mark the replies as Answered if they help and Vote if you found them helpful.

    Friday, August 03, 2012 11:20 AM
  • BTW, are you able to browse the service URL, i mean just till service1.svc?

    I suspect some issue with your service configuration. Just check if you are able to browse your service with

    localhost:port/service1.svc



    Please mark the replies as Answered if they help and Vote if you found them helpful.

    Friday, August 03, 2012 11:22 AM
  •  yes this is able to browse  with the url of http://localhost:8888/Service1.svc worked fine.



    nareshrajuu

    Friday, August 03, 2012 11:45 AM
  • i will share u r Knowledge you gave e-mail

    Thanks a lot


    nareshrajuu

    Friday, August 03, 2012 11:49 AM
  • I don't know if you have already seen JayData at http://phonegap.com/tool, which library saves you the query building, ajax result processing and provides JavaScipt objects. Check out the examples here: http://jaydata.org/examples/index.html. More PhoneGap examples can be found in the JayData blog.

    Let me know if you need any help.

    Robert

    Friday, August 03, 2012 12:14 PM
  • hi veerendra ,

    now i didnot get any error but didnot display the data from the wcf service.

    please could you help to me


    nareshrajuu

    Monday, August 06, 2012 11:09 AM
  • What changes you made? Have you looked at the sample i sent? are you able to get data using my sample?


    Please mark the replies as Answered if they help and Vote if you found them helpful.

    Monday, August 06, 2012 11:25 AM
  • Hi veerendra thanks a lot ,i couldn't able to open you sent a file with.reg extension.

    but i did like this now gettin object object error. Now didnot connect to database,

    just i want to returning the string value,

    please see here below code

    service.cs:

    [ServiceContract]
        public interface IService1
        {
              [OperationContract]
            [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
            [WebGet(UriTemplate = "/getname()")]
            string getname();

    }

    in IService.svc.cs                                                                                                                                                                    

    [AspNetCompatibilityRequirements(RequirementsMode =
                AspNetCompatibilityRequirementsMode.Allowed)]
        public class Service1 : IService1
        {

     public string getname()
            {
                return "welcome to wcf";
            }

    }

    in Index.html,

    <script>                              

    function BtnWcfService_onclick() {

                 var data = $("#data").val();
                 jQuery.support.cors = true;
                 $.ajax({
                     type: "POST",
                     url: "Service1.svc/getname",
      data:{},
                     contentType: "application/json; charset=utf-8",
                     dataType: "JSON",
                     ProcessData: false,
       success: function (msg) {
                         var theRealData = msg.d;
                         document.getElementById("welcomeMsg").innerHTML += theRealData;
                     },
                     error: function (msg) {
                         alert("error in wcf service calling : "+msg);
                     }
                 });

             }

    </script>

    <input id="BtnWcfService" type="button" value="Call WCF Data" onclick="return BtnWcfService_onclick()" />


    nareshrajuu

    Monday, August 06, 2012 1:20 PM
  • Your URI template need to be plain string

    Change this [WebGet(UriTemplate = "/getname()")]

    To

    [WebGet(UriTemplate = "/getname")]

    BTW when you dont have any elements to pass to the method you need to use GET and not POST.

    I recommend you run the solution i sent and test first. and start integrating your code in to the same.

    .reg file you have to use it to register JSON MIME type reply for the browser. Just unzip it and double click on it. it registers the MIME type for you.



    Please mark the replies as Answered if they help and Vote if you found them helpful.

    Tuesday, August 07, 2012 5:04 AM
  • hi veerendra, thanks a lot 

    i tried but no luck.

     i googled lot of time but i didn't get any example on this . i am suspecting  on phonegap version1.9.0.

    i am not sure may be it willn't  support the wcf service.

    please let me know if you have got any link about this scenario .

    thanks and regards,

    nareshrajuu


    nareshrajuu

    Thursday, August 09, 2012 8:37 AM