0

I am using the following to talk to a web api endpoint controller. The problem I am having is that it returns xml instead of json. From what I understand you need to pass the content type like below to determine the return type, that is why I have it set to JSON. I am stumped as to how to return json.

$.ajax({
    url: 'http://localhost:43043/api/main?ordernumber=33232048&category=damage',
    type: 'GET',
    contentType: "application/json; charset=utf-8",
    //data: {
    //    orderNumber: num,
    //    category: cat
    //},
    success:
           function (data) {
               var usingRoutData = document.URL;
               ko.applyBindings(new InvoiceViewModel(data));
           },

    error: function () {
        alert('failure');
    }

});
4
  • you need dataType:"json" as one of the options for the .ajax call, and of course make sure the server is outputting valid json code. Commented Jul 22, 2013 at 19:29
  • you would need to modify your server-side script and tell IT to return json. the client doesn't just take whatever is sent and convert it to your expected data format. If it's returning XML, it's a server-side problem, not client-side/javascript. Commented Jul 22, 2013 at 19:34
  • possible duplicate of How do I get ASP.NET Web API to return JSON instead of XML using Chrome? Commented Jul 22, 2013 at 19:34
  • It's all about content negotiation, Web API will choose the best fit among available formats. Disabling all formats on the web api configuration except JSON or adding an Accept header in the ajax call would be equally acceptable solutions to your problem. It all depends on whether you always need JSON responses or just this once. Commented Jul 25, 2013 at 12:45

2 Answers 2

2

I believe you need to set the Accept header setting content type header for a get request doesn't really make sense.

$.ajax({
    url: 'http://localhost:43043/api/main?ordernumber=33232048&category=damage',
    type: 'GET',
    headers: {'Accept':'application/json'}, 
    //data: {
    //    orderNumber: num,
    //    category: cat
    //},
    success:
           function (data) {
               var usingRoutData = document.URL;
               ko.applyBindings(new InvoiceViewModel(data));
           },

    error: function () {
        alert('failure');
    }

})

;

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

Comments

0

Have you tried setting the dataType property:

dataType: "json",

http://api.jquery.com/jQuery.getJSON/

1 Comment

Not enough rep to reply to Kevin B's comment above. He's using Web API which will, by default, will return the type asked for by the client (XML or JSON).

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.