How to return data from ajax call

In this post,I will show you how to return data from ajax request.As you know that you can not return data from ajax request but if you want to perform some action on return data of ajax.The better approach is to organize your code properly around callbacks. In the example,you can make GetUsers accept a callback and use it as success callback.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReturnAjax.aspx.cs" Inherits="ReturnAjax" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
        $(document).ready(function () {
            function GetUsers(name, callback) {

                    type: "POST",
                    async: true,
                    url: "ReturnAjax.aspx/GetUsers",
                    data: "{name:'" + name + "'}",
                    dataType: "json",
                    contentType: "application/json",
                    success: function (data) {
                        //Pass return data to callback function and do the operation
            $("#check").click(function () {
                GetUsers($("#txtName").val(), function (users) {
                    $.each(users, function (index, user) {
                        $('#result').append('<p><strong>' + user.UserId + ' ' + user.Name + '</br>');


    <form id="form1" runat="server">
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <input type="button" name="check" value="check " id="check" /><br />
        <div id="result">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ReturnAjax : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static UserData[] GetUsers(string name)
        return UserData.Users.Where(x => x.Name.StartsWith(name)).ToArray();
public class UserData
    public string UserId { get; set; }
    public string Name { get; set; }

    public static List<UserData> Users
            return new List<UserData>()
                          new UserData(){UserId = "1",Name = "Bill"},
                          new UserData(){UserId = "2",Name = "Booler"},
                          new UserData(){UserId = "3",Name = "Scott"},
                          new UserData(){UserId = "4",Name = "Anders"},

Post a Comment


Close Menu