user5426326
user5426326

Reputation:

Consuming WCF service in Javascript/Jquery Ajax call

I have a WCF service hosted/published on the below path -

newslettersubscriptiondev.mercola.com/NewsletterSubscriptionService.svc

Want to call above WCF service in Jquery Ajax Call

Code written in jQuery -

<script type="text/javascript" src="JS/jquery-2.1.4.js"></script>
<script type="text/javascript" src="JS/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
    function cityClickJQuery() {
        $.ajax({
            type: "POST",
            url: "http://newslettersubscriptiondev.mercola.com/NewsletterSubscriptionService.svc/CheckEmailaddressValidateOnly",
            data: { EmaillAddress: '[email protected]', Source: 'ArticleBody' },
            processData: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                alert('success');
                alert(data.d);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(JSON.stringify(jqXHR));
                console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                alert(jqXHR);
            }
        });
    }

</script>

In the above JS code CheckEmailaddressValidateOnly is the C# method defined in Service which requires 2 parameters.

Design code -

    <body>
        <form id="form1" runat="server">
        <div>
        <asp:Button ID="btn1" runat="server" OnClientClick="cityClickJQuery();" Text="click" />
        </div>
        </form> 
  </body>

Above JS code is not working.

Please Help.

Upvotes: 2

Views: 3366

Answers (2)

Shahid Manzoor Bhat
Shahid Manzoor Bhat

Reputation: 1335

First you should verify that you include attribute

[WebInvoke (ResponseFormat = WebMessageFormat.Json)]

Second you should use

data:JSON.stringify({EmaillAddress: '[email protected]', Source: 'ArticleBody'}), 

The JSON.stringify is defined in http://www.json.org/js.html.

One more update After the successful return of data you will see that the data returned back should be accessed not with data.d.EmailAddress, but with data.EmailAddress instead. ASMX web-service place the data in the property d, but not WCF service.

Upvotes: 2

Mohammed47
Mohammed47

Reputation: 117

Change data: { EmaillAddress: '[email protected]', Source: 'ArticleBody' }, To

data: JSON.stringify({ EmaillAddress: '[email protected]', Source: 'ArticleBody' }),

Upvotes: 0

Related Questions