3

I'm quite confused as to why this is happening.

I can't seem to pass data successfully via $.ajax, the URL gets all mangled up instead of the data being passed in a query string.

I've cleaned up the code for brevity, see below.

Webservice (using GET)

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string TestMethod(string country, string city)
{
    return country + city;
}

jQuery

$.ajax({
    url: "Test.asmx/TestMethod",
    type: "GET",
    data: '{"country":"' + country + '","city":"' + city + '"}',
    dataType: "json",
    success: function(msg) {
        alert(msg.d);
    }
});

Resulting URL and Error (in Firebug)

http://example.com/Test.asmx/TestMethod?{%22country%22:%22NZ%22,%22city%22:%22AK%22}
System.InvalidOperationException: Missing parameter: country.
Marko
  • 71,361
  • 28
  • 124
  • 158

2 Answers2

3

Try to change

data: '{"country":"' + country + '","city":"' + city + '"}'

To

data: "country="+country+"&city="+city

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • Or you could change the `contentType` to `application/json`. (http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/) – FishBasketGordo Sep 28 '11 at 03:05
  • @xdazz so the 'data' portion just gets appended to the URL huh? Well that's good to know haha, thanks a lot! – Marko Sep 28 '11 at 03:07
  • @Marko if it's a string yes. If it's an object no. If you remove the plings before { and after } you'd see a different behavior than the one you describe – Rune FS Sep 28 '11 at 04:09
  • @Marko make that if you removed the plings and and double plings ie { country:country, ...} – Rune FS Sep 28 '11 at 04:11
1

Adding a "contentType" property to the options list would be the easiest change in my mind.

I also use JSON.stringify() to reduce the introduction of quotation errors.

$.ajax({
    url: "Test.asmx/TestMethod",
    type: "GET",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ country: country, city: city }),
    dataType: "json",
    success: function(msg) {
        alert(msg.d);
    }
});
Erik Anderson
  • 4,915
  • 3
  • 31
  • 30