Marko
Marko

Reputation: 72222

$.ajax & passing data to .asmx webservice

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.

Upvotes: 3

Views: 5669

Answers (2)

Erik Anderson
Erik Anderson

Reputation: 5289

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);
    }
});

Upvotes: 1

xdazz
xdazz

Reputation: 160833

Try to change

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

To

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

Upvotes: 3

Related Questions