Reputation: 4140
I'm using a slightly modified version of Deebu Jacob's ASP.NET web method call using AJAX (jQuery) example here. I've modified the CodeBehind to take a string instead of an int, but if I try to send an alpha string, I get no JS Alert when I click the button. If on the other hand I send a string of digits, it works, even with blanks & decimal points. I've added a second function to allow me to send variables instead of the hardcoded example on the page, which works just fine.
I think I'm missing a concept in the contentType
or dataType
of the AJAX call, which I just don't understand yet. I've tried changing the dataType to text
and the contentType
to application/x-www-form-urlencoded; charset=UTF-8
, but was unable to get either to work.
HTML/ASP (this example works, if you change one of the variables to contain alpha characters, it won't):
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="JQueryAJAXwithIntExample.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
function asyncServerCall(userid) {
jQuery.ajax({
url: 'WebForm1.aspx/GetData',
type: "POST",
data: "{'userid':" + userid + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
}
});
}
</script>
<script type="text/javascript">
function testMe() {
var suffix = ".159";
var text = "314" + suffix;
asyncServerCall(text);
}
</script>
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="click me" onclick="testMe();" />
</div>
</form>
</body>
</html>
CodeBehind (only change is input datatype from int to string in GetData method):
using System;
using System.Web.Services;
namespace JQueryAJAXwithIntExample
{
public partial class WebForm1 : System.Web.UI.Page
{
[WebMethod()]
public static string GetData(string userid)
{
/*You can do database operations here if required*/
return "My user ID is: " + userid;
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
My ultimate goal is to pass back a string or series of strings to the server to be processed into mail & SQL objects for the Online RMA project I'm working on.
Upvotes: 0
Views: 111
Reputation: 3615
I believe this:
data: "{'userid':" + userid + "}",
Should be this:
data: "{'userid':'" + userid + "'}",
Note the single quotes around the string value.
Upvotes: 4