Praneeb Karat
Praneeb Karat

Reputation: 73

Returning data from Aspx page using JQuery & AJAX

I have a aspx page (Sample.aspx) containing just a HTML Button. In the .CS file of the aspx page i have written a small function (sample_function) which simply returns a string "Hello World". I'm trying to display that string in the Alert box when the user clicks on the button. The problem is when I click on the button the entire source code of the .aspx page is displayed in the Alert box instead of displaying "Hello World". Please help me to solve this. Below is my summerized code of Sample.aspx page.

<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#Button1").click(function () {
            $.post("Sample.aspx/sample_function",
    {

    },
    function (data, status) {
        alert("Data: " + data + "\nStatus: " + status);
    });
    });
    });
</script>

</head>
<body>
    <form id="form1" runat="server">
    <div >
    <input id="Button1" type="button" value="Click Me" /></div>
    </form>
</body>

Here is summerized version of my .cs code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication4
{
    public partial class Sample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public string sample_function()
        {
            string s1 = "Hellow World";
            return s1;
        }
    }
}

Upvotes: 1

Views: 2699

Answers (2)

Karl Anderson
Karl Anderson

Reputation: 34846

Use ASP.NET AJAX Page Methods, like this:

Code-behind:

[WebMethod]
public static string sample_function()
{
    string s1 = "Hellow World";
    return s1;
}

Note: ASP.NET AJAX Page Methods must be decorated with [WebMethod] attribute and must be static, thus they cannot interact with controls on the page, because there is no page instance.


Markup:

$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "Sample.aspx/sample_function",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            alert(result.d);
        }  
    });
});

Upvotes: 1

Jhonatas Kleinkauff
Jhonatas Kleinkauff

Reputation: 966

You must have an WebMethod.

[WebMethod]
public static string sample_function()
{
    string s1 = "Hellow World";
    return s1;
}

Upvotes: 0

Related Questions