I need some help with JavaScript as I'm a novice and I can't get the jquery ajax to call my method in code behind. I'm trying to adapt this example to my needs, but I'm not getting the expected results. Understand jQuery Ajax Function: Call Code-behind C# Method
- I cannot determine whether button "BtnAgain" is actually calling the script.
- If the button is in fact calling the script, It seems like the url in the ajax is not finding the method in the code behind.
Here is my code:
JavaScript.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="WebApplication.JavaScript" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function SaveImage() {
$.ajax({
type: "POST",
url: "JavaScript.aspx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#Content").text(response.d);
alert('Function called successfully !');
},
failure: function (response) {
alert(response.d);
}
});
});
</script>
</head>
<body>
<form id="frm" runat="server">
<div id="Content">
</div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click1" Text="ASP Button" />
<asp:Button ID="BtnAgain" runat="server" OnClientClick="SaveImage()" Text="JS Button" />
</form>
</body>
</html>
JavaScript.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace WebApplication
{
public partial class JavaScript : System.Web.UI.Page
{
[WebMethod]
public static string GetData()
{
return "This string is from Code behind";
}
protected void Button1_Click1(object sender, EventArgs e)
{
Label1.Text = GetData();
}
}
}