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\"}]"}
LVL 1
ITsolutionWizardAsked:
Who is Participating?
 
Duy PhamFreelance IT ConsultantCommented:
Your WCF REST service doesn't support JSONP, so I always got parsererror when trying to consume your service. From your ajax script on comment: http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/Q_28653962.html#a40719959, it seems that you also using cross-domain calls to your WCF REST service.

In that case, I would suggest you try to allow cross-domain script access. You can enable that from WCF REST service web.config as below
<system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="jsonpEnabled" crossDomainScriptAccessEnabled="true">
        </binding>
      </webHttpBinding>
    </bindings>
    <services>
      <service name="WcfService1.Service1" behaviorConfiguration="defBahavior">
        <endpoint address="" binding="webHttpBinding" bindingConfiguration="jsonpEnabled" contract="WcfService1.IService1" behaviorConfiguration="web"></endpoint>
      </service>
    </services>
<system.serviceModel>

Open in new window

0
 
ITsolutionWizardAuthor Commented:
{"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.
0
 
Duy PhamFreelance IT ConsultantCommented:
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

0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
ITsolutionWizardAuthor Commented:
not working. what is '.d' mean?
0
 
Duy PhamFreelance IT ConsultantCommented:
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.
0
 
ITsolutionWizardAuthor Commented:
Still not working.
0
 
Duy PhamFreelance IT ConsultantCommented:
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?
0
 
ITsolutionWizardAuthor Commented:
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
0
 
ITsolutionWizardAuthor Commented:
Can you use my response jon body and call it and use your codes as demo and see it is working or not?
0
 
Duy PhamFreelance IT ConsultantCommented:
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); } });
0
 
ITsolutionWizardAuthor Commented:
Why it is wrong when the jon is specifed.
0
 
Duy PhamFreelance IT ConsultantCommented:
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.
0
 
ITsolutionWizardAuthor Commented:
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\"}]"}
0
 
ITsolutionWizardAuthor Commented:
I know I added more parameters but the logic is the same.
0
 
ITsolutionWizardAuthor Commented:
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
0
 
Duy PhamFreelance IT ConsultantCommented:
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.
0
 
ITsolutionWizardAuthor Commented:
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.
0
 
ITsolutionWizardAuthor Commented:
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.
0
 
ITsolutionWizardAuthor Commented:
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>
0
 
ITsolutionWizardAuthor Commented:
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.