Lloyd Powell
Lloyd Powell

Reputation: 18770

Ajax requesting WCF data (in JSON format) but reaching error with success message

I've been trying to resolve my issue with this answer but I'm having no luck.

Overall, I've created a WCF project with a number of functions in which I would like to access via AJAX (via javascript in my html page).

Here's an example of a function within my web service:
iService

[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json)]
string GetStuff();

Service

    public string GetStuff()
    {
        string url = string.Format("http://myapi.co.uk/api/mystuff");

        WebRequest myReq = WebRequest.Create(url);

        // Where USERNAME and PASSWORD are constants
        string usernamePassword = USERNAME + ":" + PASSWORD;
        CredentialCache mycache = new CredentialCache();
        mycache.Add(new Uri(url), "Basic", new NetworkCredential(USERNAME, PASSWORD));
        myReq.Credentials = mycache;
        myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));

        WebResponse wr = myReq.GetResponse();
        Stream receiveStream = wr.GetResponseStream();

        StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
        string content = reader.ReadToEnd();

        return content;
    }

Please note that I have also tried returning the Stream directly also.

Over to my javascript and ajax!

function getData()
{
  jQuery.support.cors = true;

  $.ajax({
      type: "GET",
      url: "http://localhost:15574/Service1.svc/GetStuff",
      contentType: "application/json; charset=utf-8",
      dataType: "jsonp",
      success: function(result) {
         alert(result);
      },
      error: function(msg) {
        alert("Fail: " + msg.status + ":" + msg.statusText);
      }
   });
}

I hit the error section, but strangely with a success error message...

Error Message

I originally thought the issue was because the JSON from the external API was incorrectly formatted, but I tried changing my web service to return some perfectly valid JSON and the same error was displayed. Like I mentioned also, I tried changing my webservice to return the Stream but I had no luck.

Any help with this would be appreciated and I would be very grateful.

Updates

P.S. It appears to work fine in WCF Test Client, returning a string with what I expect.
P.P.S Just added another parameter to the error function to get its status, I'm getting parsererror P.P.P.S The 3rd parameter passed to error is jquery171014696656613195724_1341477967656 was not called

Upvotes: 3

Views: 793

Answers (2)

volpav
volpav

Reputation: 5128

Just a quick guess: You're using WebInvokeAttribute but trying to call a service operation using HTTP GET. Default value for Method property of the WebInvokeAttribute is POST (MSDN). Try switching to WebGetAttribute:

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string GetStuff();

Alternatively you can set the Method property of the WebInvokeAttribute to GET.

UPDATE

As @Cheeso mentioned, the "Parse error" that you get is due to the fact that the JavaScript engine cannot interpret the data that you're returning because it's just a plain JSON which itself is not a valid expression (imagine that you put it inside the <script></script> tags. This obviously won't work and this is exactly what the browser tries to do).

You need to respect the callback parameter and wrap you response so it becomes a parameters of the function whose name is passed via callback parameter:

// If the ASP.NET compatibility was enabled, you could safely use HttpContext.Current
// It's here just to demonstrate the idea
return string.Format("{0}({1});", HttpContext.Current.Request.QueryString["callback"], content);

Alternatively just set the "dataType" to "json" when making AJAX call.

Upvotes: 1

Cheeso
Cheeso

Reputation: 192417

You have dataType : 'jsonp' in your jquery code. This tells jQuery to append a callback=XXXX to the URL.

The server-side of this dialogue needs to wrap the JSON result in that callback. But your code doesn't do that.

Are you sure you want jsonp?

You might be able to fix this by using dataType: 'json'

Upvotes: 1

Related Questions