2

Been trying my best to understand this correctly. What is the difference between an XML, SOAP and JSON response? And how does one know how to call a web service whose response is one of the above? (...Please correct me if I'm off-track)

The reason I ask this because I am trying to call a remote ASMX from jQuery within my .NET3.5 webapp, and no luck at all!! Basically I am trying to call a CurrencyConverter method as shown at this address: http://www.webservicex.net/CurrencyConvertor.asmx?op=ConversionRate

I can see that it returns XML, but the following code does not work:

$('#Currency').bind('change', function() {
    var targetDiv = '#Result'
    var currencyValue = $('#Currency option:selected').attr('value')
    var webMethod = 'http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate'
    var parameters = "{'FromCurrency':'GBP','ToCurrency':'" + currencyValue + "'}"

    $(targetDiv).html('loading...');

    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            $(targetDiv).html(response.d);
        },
        error: function(response) {
            $(targetDiv).html("Unavailable:" + response);
        }
    });
});

Please could someone assist me with this, as I am really lost!

Thank you!

Community
  • 1
  • 1
Shalan
  • 943
  • 4
  • 20
  • 43

4 Answers4

4

I have used this web service before. It expects and returns XML. Here's the code I used to get to work in Internet Explorer (For Firefox you need to use the jsonp).

$('#Currency').bind('change', function() {
    var targetDiv = '#Result'
    var currencyValue = $('#Currency option:selected').val();
    var webMethod = 'http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate';
    var parameters = "?FromCurrency=GBP&ToCurrency=" + currencyValue;

    $(targetDiv).html('loading...');

    $.ajax({
        type: "GET",
        url: webMethod + parameters ,
        contentType: "text/xml; charset=utf-8", 
        dataType: "xml", //for Firefox change this to "jsonp"
        success: function(response) {
            $(targetDiv).html(response.text);
        },
        error: function(xhr, textStatus, errorThrown) {
            $(targetDiv).html("Unavailable: " + textStatus);
        }
    });
)};
Jose Basilio
  • 50,714
  • 13
  • 121
  • 117
  • Hey Jose! Thanks for this. I see a bit of light now...when I change the selectedValue of the select element, I see "waiting for www.webservicex.net" flash for about a second, then nothing :( – Shalan May 28 '09 at 23:39
  • in the statusbar i meant to say – Shalan May 28 '09 at 23:55
  • Hi Jose. No I havent tested in IE yet. Just installed IE8 so need to restart my machine. Something interesting tho. I invoked the dropdown change event, and payed attention to whats happening in Fiddler - I received an HTTP 200 OK Response and under the TextView of the Inspectors I see the following: 1.6039 So ITS WORKING!! :) but nothing happening in Firefox...so it must be something to do with the way the response is being handled in success. Hope this helps you a bit to help me. Thanks! – Shalan May 29 '09 at 08:10
  • should I also be doing something to my web.config? I cant imagine why I would as Im purely using jQuery to execute and request the response – Shalan May 29 '09 at 08:13
  • Here is more info if it will help: REQUEST ------- GET /CurrencyConvertor.asmx/ConversionRate?FromCurrency=GBP&ToCurrency=USD&callback=jsonp1243585024463&_=1243585056256 HTTP/1.1 Host: www.webservicex.net User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729) Accept: */* Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Referer: http://localhost:1654/TestApp/default.aspx – Shalan May 29 '09 at 08:21
  • RESPONSE -------- HTTP/1.1 200 OK Date: Fri, 29 May 2009 08:17:35 GMT Content-Length: 99 Content-Type: text/xml; charset=utf-8 Cache-Control: private, max-age=0 Server: Microsoft-IIS/6.0 X-Powered-By: ASP.NET X-AspNet-Version: 2.0.50727 1.6067 – Shalan May 29 '09 at 08:22
  • OK! Tested in IE and IT WORKS 99%! I say 99%, because when I change the index of the dropdown, it prompts me with "This page is accessing information that is not under its control. This poses a security risk. Do you want to continue"....Any way to avoid this prompt? I know James below made the suggestion of creating a local proxy service to access the remote service, and then call the local service from jQuery. would that work?? – Shalan May 29 '09 at 11:55
  • Also, it works in IE, but not in FF3. Even if I change the dataType to 'jsonp'. I would like for this to be x-browser compatible as far as possible. Sorry for the load of comments. Was initially anxious to see it work for the 1st time, and now that it does somewhat, I absolutely LOVE IT!! – Shalan May 29 '09 at 11:58
  • From my research, aside from creating a local proxy, there's really no way to get around this issue since the service is out of your control. – Jose Basilio May 29 '09 at 12:19
  • The webservice from webserviceX.NET returns only XML, it does not return JSON. In order for jsonp to work, the service needs to support that. For more information read this article: http://www.ibm.com/developerworks/library/wa-aj-jsonp1/ – Jose Basilio May 29 '09 at 16:36
  • Hi. thanks for the response. I understand the limitations. I think James' code below will certainly help. Also, h ave a look at this article: http://elegantcode.com/2008/12/02/calling-remote-aspnet-web-services-from-jquery/ and tell me if this will be a good start in helping me resolve my issues? – Shalan May 31 '09 at 20:39
  • I had read that article before, but like I already mentioned, this will not help you in this particular case because webserviceX returns only XML and not JSON. – Jose Basilio May 31 '09 at 21:01
  • OK :( sorry for asking again, but is it possible that whilst setting up a proxy as a 'bridge' between the remote service and client script, that I can somehow parse the XML response as JSON? Im not looking for a code example...I'll be more than happy if you can point me in the right direction of where I need to look. Thank you for all your help, Jose! – Shalan Jun 01 '09 at 15:30
  • If that were an option, I would have mentioned it to you. The problem is that the code that receives the Ajax response using "jsonp" is internal to jQuery, you would have to dig into the jQuery source and create your own implementation (a very complex task indeed). – Jose Basilio Jun 01 '09 at 15:48
  • Thanks for the reply. So is there NO way at all for me to consume this webservice? – Shalan Jun 01 '09 at 17:26
  • Not without creating your own proxy – Jose Basilio Jun 02 '09 at 18:43
2

[Edit] Another thing you could try is to change the dataType in the JQuery call to "xml". If that doesn't work, you could make your own proxy Web-Service that calls the remote one, and then return the data in a JSON format.

I suspect the problem is in the server side code. I'm not sure if this will work for you but here is some working code that shows JQuery calling my WebMethod. Hopefully you can compare this with yours and get it working. Let us know what the solution is. I hope this helps.

[Server Code]

using System;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    [ScriptService]
    public class ForumService : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public VoteCastResult CastQuestionVote(string itemID, QAForum.Bll.VoteType voteType)
        {
            try
            {
                User usr = SecurityHelper.GetOrCreateUser();
                Guid question = new Guid(itemID);
                return new QuestionVoteController().CastQuestionVote(usr, question, voteType);
            }
            catch (Exception ex)
            {
                return new VoteCastResult(VoteCastStatusType.otherIssue, 0, ex.Message);
            }
        }
    }


[JQuery Code]

    function AFTopicCastVote(clickContext, itemID, voteDirection, voteMethod)
    {
          $.ajax({
          type: "POST",
          contentType: "application/json; charset=utf-8",
          url: (AFServiceUrl + voteMethod),
          data: "{'itemID': '" + itemID + "','voteType': '" + voteDirection + "'}",
          dataType: "json",
          success: function (data, textStatus) {
                               AFTopicProcessVoteResult(clickContext, data.d);
                                //alert("data : " + data.d);
                            },

          error: function (  XMLHttpRequest, textStatus, errorThrown) 
          {
            alert("error casting vote: " + errorThrown);
          }
        });    
    }
James
  • 12,636
  • 12
  • 67
  • 104
1

in page load function add the next lines for a client ....

        base.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        base.Response.AddHeader("Access-Control-Allow-Headers", "X-Requested-With");
        base.Response.AddHeader("Access-Control-Max-Age", "86400");
Frastro
  • 11
  • 1
0

The problem has to do with Cross-Site posting. You may be getting the error "Access to restricted URI denied code: 1012" because you are posting to a WebService in another domain.

Please refer this post on Error 1012

Community
  • 1
  • 1
ichiban
  • 6,162
  • 3
  • 27
  • 34
  • I figured as much, but then shouldn't I have got a response with that error in my alert (as per James suggestion above)? Is there any other way to do this? I know there must be, cos that's why these services are there - to be consumed! :) – Shalan May 28 '09 at 22:35
  • This error does not show in the response becuase the call to web service does not even occur. The error shows up in Firebug. Check out this other post: http://stackoverflow.com/questions/51283/access-to-restricted-uri-denied-code-1012 – ichiban May 28 '09 at 22:37