Not sure what I’m doing wrong but I can’t get my JQuery AJAX call to pass the variable properly. It recieves it just fine. I’m probably overlooking something minor. Thanks.
(Also, is there any way to pass data this way without using a [WebMethod] or via the URL?)
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('#button').click(function(){
var json_obj = "{'" + $('#t1').val() + "' : '" + $('#p1').val() + "', '" + $('#t2').val() + "' : '" + $('#p2').val() + "'}";
$.ajax({
type: "POST",
url: 'Default.aspx/test',
contentType: 'application/json; charset=utf-8',
data: "thisisatest",//json_obj,
dataType: 'json',
success: function(msg) {
//$('#result').html(msg.d);
alert(msg.d)
},
error: function(msg) {
//$('#result').html(msg.d);
alert(msg.d + " err")
}
});
});
});
</script>
</head>
<body>
<div>
Type: 1: <input type="text" id="t1" />
Property 1: <input type="text" id="p1" />
<br /><br />
Type 2: <input type="text" id="t2" />
Property 2: <input type="text" id="p2" />
<input type="button" value="Add object!" id="button" />
<br /><br />
<div id="result"></div>
</div>
</body>
</html>
Code Behind
[WebMethod]
public string test(string json)
{
return json;
}
Here’s a full example I wrote for you to illustrate the concept:
I have mixed here the code behind and the markup in the same
Default.aspxfile but obviously you could have them separate if you prefer.