Link to home
Start Free TrialLog in
Avatar of ITsolutionWizard
ITsolutionWizardFlag for United States of America

asked on

jquery

How to code for consuming GetNetPriceTest by using Jquery?

I just need to do something like

<div>
Id: 1
Name:066
</div>


WCF Interface
#region GetNetPriceTest
        [OperationContract]
        [WebGet(ResponseFormat=WebMessageFormat.Json, UriTemplate = "ProQuoteService/GetNetPriceTest({CompanyID})") ]
        String GetNetPriceTest(string CompanyID);
        #endregion


Code:
 public string GetNetPriceTest(string CompanyID)
        {
            TokenPackage ret;
            List<object> customers = new List<object>();
            customers.Add(new
            {
                Id = "1",
                Name = CompanyID
            }
            );
            ret = new TokenPackage { PackageNo = 1, TotalPackages = 1, Status = StatusCodes.Ok, Data = Newtonsoft.Json.JsonConvert.SerializeObject(customers) };
            //return (new JavaScriptSerializer().Serialize(customers));
            return (new JavaScriptSerializer().Serialize(ret));
        }

       
Return Record from wcf restful webservice:
{"PackageKey":null,"PackageNo":1,"TotalPackages":1,"Status":"Ok","Data":"[{\"Id\":\"1\",\"Name\":\"066\"}]"}
Avatar of ITsolutionWizard
ITsolutionWizard
Flag of United States of America image

ASKER

{"PackageKey":null,"PackageNo":1,"TotalPackages":1,"Status":"Ok","Data":"[{\"Id\":\"1\",\"Name\":\"066\"}]"}

I already verified the output on http://jsonlint.com/, and it looks good as well.
Avatar of Duy Pham
Example jQuery call:
$.ajax({
        url: 'http://yourwcfservicehost/service-base-uri/ProQuoteService/GetNetPriceTest(' + companyID + ')',
        type: "GET",
        contentType: "application/json; charset=utf-8",
        success: function(msg) {
            var response = $.parseJSON(msg.d);
            alert(response.Status + ': Data.Id = ' + response.Data.Id + ', Data.Name = ' + response.Data.Name);
        }
    });

Open in new window

not working. what is '.d' mean?
Try to replace var response = $.parseJSON(msg.d); with var response = $.parseJSON(msg);.

d is just a wrapped property when using ajax to call Web Service methods. Maybe your RESTful WCF service does return only plain JSON string.
Still not working.
Could you please be more specific? What does not work? Do you success in calling your RESTful WCF Service? And what data is returned in msg on success?
No data return.
But when I check with chrome f12
It shows the response text in a correct result, and status is 200 as well
Can you use my response jon body and call it and use your codes as demo and see it is working or not?
My script could be wrong if you specify ResponseFormat = WebMessageFormat.Json in your WCF RESTful service method. Below are my test service and ajax call which works just fine.

Service Interface
[ServiceContract] public interface IService1 { [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "json/company({companyId})")] CompositeType GetData(string companyId); } [DataContract] public class CompositeData { [DataMember] public string Id { get; set; } [DataMember] public string Name { get; set; } } // Use a data contract as illustrated in the sample below to add composite types to service operations. [DataContract] public class CompositeType { [DataMember] public string PackageKey { get; set; } [DataMember] public int PackageNo { get; set; } [DataMember] public int TotalPackages { get; set; } [DataMember] public string Status { get; set; } [DataMember] public CompositeData Data { get; set; } }
Service Implementation
public class Service1 : IService1 { public CompositeType GetData(string companyId) { return new CompositeType() { PackageKey = null, PackageNo = 1, TotalPackages = 1, Status = "OK", Data = new CompositeData() { Id = companyId, Name = "066" } }; } }
Ajax Call from client
$.ajax({ url: 'http://localhost/WcfService1/Service1.svc/json/company(1)', type: "GET", contentType: "application/json; charset=utf-8", success: function (msg) { var response = msg; alert(response.Status + ': Data.Id = ' + response.Data.Id + ', Data.Name = ' + response.Data.Name); } });
Why it is wrong when the jon is specifed.
When ResponseFormat = WebMessageFormat.Json is specified, the actual response data is an JSON object, and you don't have to parse it like when response data is a json string. And you can just use the returned JSON object just like in my sample ajax call above.
http://clientaccesstest.kenwoodusa.com/wcf/proquotes/RestService/ProQuoteServiceJVC/GetNetPriceTest(062,337557,[KDAV300],[5],1,SA7)

I do not think yours working. I use above services and still not working using your codes.
the return result is:

{"PackageKey":null,"PackageNo":1,"TotalPackages":1,"Status":"Ok","Data":"[{\"Status\":\"Completed\",\"NetPrice\":\"118.490\",\"ListPrice\":\"140.350\"}]"}
I know I added more parameters but the logic is the same.
So far below is what I have.
The codes below working on IE. but not Chrome/Firefox. I used your codes sample.
I also attached the error message from Firefox.

I also try to get individual item but not working.

<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
        function GetNetPrice() {
          var GetNetPriceJson = 'http://clientaccesstest.kenwoodusa.com/wcf/proquotes/RestService/ProQuoteServiceJVC/GetNetPriceTest(062,337557,[KDAV300],[5],1,SA7)';
            {
                $(document).ready(function () {
                    $.ajax({
                        crossDoamin: true,
                        cache: false,
                        type: "GET",
                        async: false,
                        dataType: "json",
                        contentType: 'text/plain',
                        url: GetNetPriceJson,
                        success: function (msg) {
                            var response = msg;
                            //alert(response.Data.NetPrice); not working
                            alert(msg);
                        },
                        error: function (xhr) {
                             alert(xhr.responseText + " : error GetNetPrice");
                        }
                    });
                });
            }
        }
</script>
err1.png
Well, my example works just fine. I can't upload the files here due to EE's policies. But you can try to create WCF REST Service with above code (Service1) and a sample Web Application to consume the service using $.ajax.

When I tried to call your test REST uri http://clientaccesstest.kenwoodusa.com/wcf/proquotes/RestService/ProQuoteServiceJVC/GetNetPriceTest(062,337557,[KDAV300],[5],1,SA7). I could see that I got 200 response, but $.ajax failed to parse the json result.
Try below code and you can see (parsererror as textStatus):
          $.ajax({
url: 'http://clientaccesstest.kenwoodusa.com/wcf/proquotes/RestService/ProQuoteServiceJVC/GetNetPriceTest(062,337557,[KDAV300],[5],1,SA7)',
                type: "GET",
                dataType: "jsonp",
                crossDomain: true,
                contentType: "application/json; charset=utf-8",
                success: function (msg) {
                    var response = msg;
                    alert(response.Status + ': Data.Id = ' + response.Data.Id + ', Data.Name = ' + response.Data.Name);
                },                
                error: function (jqXHR, textStatus, errorThrown) {
                    alert('failed: ' + textStatus + ' - ' + errorThrown);
                }
            });

Open in new window

If you look into your returned string, it isn't a valid JSON format:
There is a lot of \.
This is what I got from response text in Chrome - Developer Tools: "{\"PackageKey\":null,\"PackageNo\":1,\"TotalPackages\":1,\"Status\":\"Ok\",\"Data\":\"[{\\\"Status\\\":\\\"Completed\\\",\\\"NetPrice\\\":\\\"118.490\\\",\\\"ListPrice\\\":\\\"140.350\\\"}]\"}".
If you try my sample WCF REST service above, the returned string is {"Data":{"Id":"1","Name":"066"},"PackageKey":null,"PackageNo":1,"Status":"OK","TotalPackages":1}.
There is an error at "Data":"[{...}]". Data isn't really a array of object, but is a string. Of course it isn't really a problem, just logic issue.

So I suggest you review your service code to see how your JSON response is created/formatted. I have tried to change contentType of ajax call to different types, but no success.
this is the result from the web service

http://clientaccesstest.kenwoodusa.com/wcf/proquotes/RestService/ProQuoteServiceJVC/GetNetPriceTest(062,337557,[KDAV300],[5],1,SA7)

{"PackageKey":null,"PackageNo":1,"TotalPackages":1,"Status":"Ok","Data":"[{\"Status\":\"Completed\",\"NetPrice\":\"118.490\",\"ListPrice\":\"140.350\"}]"}

do you see something different? And this result is exactly what i provided and it is valid json format.
or you can try this service

http://clientaccesstest.kenwoodusa.com/wcf/orders/RestService/ProQuoteServiceJVC/GetNetPrice(062,337557,[KDAV300],[5],1,SA7)

It returns xml format. I do not see any issues in codes for the return. and see you can actually consume it.
ASKER CERTIFIED SOLUTION
Avatar of Duy Pham
Duy Pham
Flag of Viet Nam image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I do not think we have cross domain issue because I have another web service call working with below codes
This is Json enabled wcf as well.

<script type="text/javascript">
        function GetModelList() {
            var GetModelListJSon = "serviceURL";
            $(document).ready(function () {
                $.ajax({
                    crossDomain: true,
                    cache: false,
                    type: "GET",
                    async: false,
                    dataType: "json",
                    contentType: 'text/plain',
                    url: GetModelListJSon + encodeURIComponent("(066,315217)"),
                    success: function (data) {
                        if (data == null)
                            return;
                        resultObj = jQuery.parseJSON(data);
                        var nestedData = jQuery.parseJSON(resultObj.Data);
                        $.each
                    (
                    nestedData, function (i, item) {
                        $("#SelectModel").append("<option value='" + item.ModelNo + "'>" + item.ModelNo + " - " + item.ModelName + " - " + formatCurrency(item.ListPrice) + "</option>");
                    }
                    )
                    },
                    error: function (xhr, status, error) {
                        //$('#data').html(xhr.responseText);
                        alert(xhr.responseText + " : error GetModelListJSon");
                        alert(status);
                        alert(error);
                    }
                });
            });
        }
</script>