0

I have a simple WCF service which returns a list of strings in JSON format. The WCF service code is shown below:

Web.config:

<system.serviceModel>
    <services>
        <service name="WcfServiceProto.Service1" 
                 behaviorConfiguration="ServiceBehavior1">
            <endpoint 
                address="" 
                behaviorConfiguration="EndPointBehavior"
                binding="webHttpBinding" 
                contract="WcfServiceProto.IService1" />
            <!--<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>-->
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="ServiceBehavior1">
                <serviceMetadata httpGetEnabled="true"/>
                <serviceDebug includeExceptionDetailInFaults="true"/>
            </behavior>
        </serviceBehaviors>
        <endpointBehaviors>
            <behavior name="EndPointBehavior">
                <webHttp />
            </behavior>
        </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>

Service1.cs:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]     
public class Service1 : IService1
{
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, 
                   BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public List<string> AutoCompleteSearch(string query)
        {
            List<string> data = new List<string>(new string[] { "AB11", "AB12", "AB13", "BC11", "BC12", "BC13", "BC14", "CD11", "CD12", "CD13", "CD14", "CD15", "CD16", "CD17", "CD18", "CD19", "CD20", "CD21", "CD22", "CD23", "CD24", "CD25", "CD26", "CD27", "CD28", "CD29", "CD31", "CD32", "CD33", "CD34", "CD35", "CD36", "CD37", "CD38", "CD39", "CD41", "CD42", "CD43", "CD44", "CD45", "CD46", "CD47", "CD48", "CD49", "CD51", "CD52", "CD53", "CD54", "CD55", "CD56",});
            List<string> results = data.Where(item => item.ToUpper().StartsWith(query.ToUpper())).ToList();
            return results;
        }
    }

I am trying to call this service using JQuery ajax as given below:

<script>    
    $(document).ready(function () {
        //alert("Hey");
        SearchText();
        function SearchText() {
            $("#Tags").autocomplete({
                source: function (request, response) {
                    alert($('#Tags').val());
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "http://localhost:59227/Service1.svc/AutoCompleteSearch",
                        data: JSON.stringify({ query: $('#Tags').val() }),
                        dataType: "json",
                        dataFilter: function (data) { return data; },
                        success: function (data) {
                            alert("called");
                            response($.map(data, function (item) {
                                return { value: item };
                            }));
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
                        }
                    });
                }
            });
        }
    });
</script>

However I do not see the list as I type in the textbox. I only see an alert with text "error" on it and no error details. I have also inserted breakpoint in WCF service but it never gets hit. Please let me know what I am doing wrong over here.

Browser console log:

OPTIONS 
XHR 
http://localhost:59227/Service1.svc/AutoCompleteSearch


Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encodingg zip, deflate
Accept-Language en-US,en;q=0.5
Access-Control-Request-Headers content-type
Access-Control-Request-Method POST
Connection keep-alive
Host localhost:59227
Origin http://localhost:49910
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 
Firefox/48.0
7
  • 1
    You can try to replace data: JSON.stringify({ query: $('#Tags').val() }), by data: { query: $('#Tags').val() }, . Moreover what is the content of errorThrown ? Commented Aug 22, 2016 at 9:27
  • I just did it but no luck. Commented Aug 22, 2016 at 9:31
  • Can you share the content of the browser console ? Commented Aug 22, 2016 at 9:55
  • Did you try putting WebInvoke attributes over your Operational Contract (method in interface IService1). Also try setting UriTemplate propery as well. And IMO, this should ideally be a GET request, not POST. [WebInvoke(Method=“GET”, ResponseFormat=WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped, UriTemplate=“AutoCompleteSearch?query={query}” )] Commented Aug 22, 2016 at 10:10
  • I have done it but still its not working. I have modified the attribute as: [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "AutoCompleteSearch?query={query}")] Commented Aug 22, 2016 at 10:17

1 Answer 1

2

Provide the WebInvoke attributes over your Operational Contract (method in interface IService1). Also try setting UriTemplate propery as well. IMO, this should ideally be a GET request, not POST.

[WebInvoke(Method=“GET”, ResponseFormat=WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped, UriTemplate=“AutoCompleteSearch?query={query}” )]

Once you have modified your service layer, update your $.ajax to use GET as type/ use $.get() and pass the argument as query string with name "query".

function SearchText() {
        $("#Tags").autocomplete({
            source: function (request, response) {
                alert($('#Tags').val());
                var url = "http://localhost:59227/Service1.svc/AutoCompleteSearch?query="+$('#Tags').val();
                $.get(url)
                  .done(function(data){ // your success code goes here})
                  .fail(function(ex){ // you failure code goes here});
            }
        });
    }

I havent tested the $.get method, have a look here in case you have any issues - https://api.jquery.com/jquery.get/

Sign up to request clarification or add additional context in comments.

3 Comments

Can you please give me equivalent ajax get call in this instance?
Is there any way I can use $.ajax in this instance as well?
@gliese581g- yes, you can. $.get is just a sugercoating over $.ajax. In your $.ajax stuff, update the url as I have given and change the type from POST to GET.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.