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!

4
  • If you set the dataType: to text and alert the response variable in the success routine does it appear as JSON or XML? Commented May 28, 2009 at 22:26
  • It's easier to just get FireBug or Fiddler to take a deeper look. Commented May 28, 2009 at 22:30
  • hi James. thanks for the reply! Just tried that, but still nothing...the label#Result just stays on "Loading..." Commented May 28, 2009 at 22:31
  • are you using Internet Explorer? Commented May 28, 2009 at 23:03

4 Answers 4

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);
        }
    });
)};
Sign up to request clarification or add additional context in comments.

16 Comments

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 :(
in the statusbar i meant to say
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="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!
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
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: localhost:1654/TestApp/default.aspx
|
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);
          }
        });    
    }

1 Comment

This is a public external web service not under his control
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");

Comments

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

2 Comments

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! :)
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: stackoverflow.com/questions/51283/…

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.