Reputation: 302
I am having some issues with Passing Parameters in a jQuery ajax call to an ASP.NET webmethod and it is BUGGING me all day long.
I've seen the solution of how it is being done and yet it is not working for me.
Here is some code:
function GetString() {
var name = "yan";
var fam = "key";
alert(name + " " + fam);
$.ajax
({
type: "GET",
url: "'Services/MyService.asmx/returnString",
dataType: "json",
//data: "{ 'fname' : '" + name + "' , 'lname' : '" + fam + "'}",
//data: "{ 'fname' : 'name' , 'lname' : 'fam'}",
//data: '{"fname":"Chris","lname":"Brandsma"}',
data: "{'fname':'Chris','lname':'Brandsma'}",
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) //what to do if fails
{
alert('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
},
success: function (data) //what to do if succedded
{
alert(data.d);
}
});
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string returnString(string fname, string lname)
{
return ("my name is " + fname + " " + lname);
}
and that's the error I get:
You can see that I've tried several ways of accomplishing it, none worked. Can anybody point the mistake/ suggest another solution???
thanks in advance
Upvotes: 0
Views: 10195
Reputation: 302
After I've been trying in the last 24 hours, I've finally succeded :) Here's how it goes:
Code Behind:
[WebMethod]
[ScriptMethod(UseHttpGet=false)]
public string returnString2(string fname, string lname)
{
return "{ \"FirstName\" : "\" + fname + "\" , \"LastName\" : "\" + lname + "\"}";
}
Notice that the (UseHttpGet=false)
Jquery:
function GetString2() {
var name = "yan";
var fam = "key";
alert(name + " " + fam);
$.ajax
({
type: "POST",
url: 'Services/MyService.asmx/returnString2',
dataType: "json",
data: JSON.stringify({ fname: "yan" , lname: "key" }),
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) //what to do if fails
{
alert('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
},
success: function (data) //what to do if succedded
{
alert(data.d);
var person = $.parseJSON(data.d);
alert(person.FirstName);
}
});
}
Notice how type:"Post"
and that data
line are changed
Thanks everyone who tried to help, all of you contributed a little bit :)
Upvotes: 3