0
votes
$.ajax({ 
  type: "POST", 
  url: "WebService.asmx/AddVisitor",
  data: "{'fname':'dave', 'lname':'ward'}", 
  contentType: "application/json; charset=utf-8", 
  dataType: "json"
});


I have an Asp.Net WebMethod that takes a firstName, lastName.....as a parameter, how do I send that stuff to that method using the JQuery Ajax method. if i hardcode the above it works without any problem

but if i pass dynamic it fails

var firstName = $("[id$='txtFirstName']");
var lastName = $("[id$='txtLastName']");

//data: "{'firstName':'Chris','lastName':'Brandsma'}"<br>

data: "{'firstname':'" + escape(firstName.val()) + "','lastName':'" + escape(lastName.val()) + "'}",

my WebMethod looks like this

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class VisitorWS : System.Web.Services.WebService {
[WebMethod]
public bool AddVisitor(string firstName, string lastName)
{
return true;
}


what wrong here? i have tried with eval and escape none of that works.

Thanks for any help.

3

3 Answers

0
votes

From what I can tell your code to set the data looks fine. The problem must be with getting the values of first name and last name. Have you tried showing the values in an alert after you get them, just to make sure that they have values?

On a possibly unrelated note, you might be interested in this article about the method of selection that you're using...

http://encosia.com/2009/06/09/11-keystrokes-that-made-my-jquery-selector-run-10x-faster/

Hope this helps!

0
votes

I'm not using the WebService stuff anymore, but do you have the [ScriptMethod] attribute as well?

Be sure to check FireBug to see what the actual error returned is. Could be a 404 which is a very different issue.

0
votes

i have figured out and here it works without adding scriptmethod to it.

var myData = { 
  "firstName": escape($('#txtFirstName').val()),
  "lastName": escape($('#txtLastName').val())
};

$.ajax({
  // ...  
  data: JSON.stringify(myData),
  // ...
});