Reputation: 417
Ultimately, I'd like to send a value to the server on a button click and query my DB. For now, I'm having trouble using jquery.ajax to call a function on the server side. Here is my code:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ajax.aspx.cs" Inherits="WebApplication1.ajax" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript" src="/Scripts/jquery-1.6.2.min.js"></script>
<script language="Javascript" type="text/javascript">
if (jQuery) { alert("jQuery loaded"); }
function send()
{
$.ajax(
{
type: "get",
url: "ajax.aspx/Test",
data: { name: 'ok' },
success: function (result) { alert("successful!"); }
})
}
</script>
<input type="button" runat="server" value="TryMe" onclick="send()" />
</asp:Content>
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string Test(string sendData)
{
return String.Format("Hello {0}", sendData);
}
Upvotes: 2
Views: 21453
Reputation: 96561
There are a couple of things which are not quite correct:
Full example:
function send() {
$.ajax({
type: "POST",
url: "ajax.aspx/Test",
data: '{ sendData: "ok" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
});
}
This code works for me.
Upvotes: 1
Reputation: 1321
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/ this link could be usefull
EDIT: your ajax call have to look like this:
$.ajax(
{
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax.aspx/Test",
data: "{ sendData: 'ok' }",
success: function (result) { alert("successful!"); }
})
Upvotes: 5