views:

1828

answers:

3

Hi there.

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!

A: 

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

ichiban
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
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
+2  A: 

[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
This is a public external web service not under his control
ichiban
ichiban: Good catch, i'll update my comment.
James
+4  A: 

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
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
in the statusbar i meant to say
Shalan
Did you test it in IE? I don't know if it works in FF.
Jose Basilio
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:<?xml version="1.0" encoding="utf-8"?><double xmlns="http://www.webserviceX.NET/">1.6039</double>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
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
Here is more info if it will help:REQUEST-------GET /CurrencyConvertor.asmx/ConversionRate?FromCurrency=GBP 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.5Accept-Encoding: gzip,deflateAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7Keep-Alive: 300Connection: keep-aliveReferer: http://localhost:1654/TestApp/default.aspx
Shalan
RESPONSE--------HTTP/1.1 200 OKDate: Fri, 29 May 2009 08:17:35 GMTContent-Length: 99Content-Type: text/xml; charset=utf-8Cache-Control: private, max-age=0Server: Microsoft-IIS/6.0X-Powered-By: ASP.NETX-AspNet-Version: 2.0.50727<?xml version="1.0" encoding="utf-8"?><double xmlns="http://www.webserviceX.NET/">1.6067</double>
Shalan
sorry about the formatting :$
Shalan
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
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
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
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
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
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
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
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
Thanks for the reply. So is there NO way at all for me to consume this webservice?
Shalan
Not without creating your own proxy
Jose Basilio