Monday, March 19, 2012

JQuery Ajax method to call server side function without postback


Client Code:
<div>
        <h3>
            This is AutoSave demo!</h3>
        <div>
            <textarea id="ContentTextarea" cols="50" rows="10"><%=HttpContext.Current.Session["UserContent"]%>  "Balajiprasad"</textarea>
            <input type='text' value='<%=HttpContext.Current.Session["UserContent"]%>' ></label>
            <br />
            <button id="SaveContentButton">
                Save</button>
            <span id="autosaveUpdates"></span>
        </div>
    </div>

    <script type="text/javascript">
        function SaveDataViaAjax(autosaveMode) {
            $("#autosaveUpdates").html("Saving ... ");

            methodURL = "Default2.aspx/SaveContent";
            parameters = "{'content':'" + $("#ContentTextarea").val() + "', 'autosave':'" + autosaveMode + "'}";

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: methodURL,
                data: parameters,
                dataType: "json",
                async: true,
                success: function (data) {
                    if (autosaveMode) {
                        $("#autosaveUpdates").html("Autosave at " + Date().toLocaleString());
                    }
                    else {
                        $("#autosaveUpdates").html("Data have been saved at " + Date().toLocaleString());
                    }
                },
                error: function (result) {
                    alert("Due to unexpected errors we were unable to load data" + result);
                }
            });
        };

        $(document).ready(function () {
            $("#SaveContentButton").click(function (event) {
                SaveDataViaAjax(true)
                event.preventDefault();
            });
        });
    </script>


Server Code:

    [WebMethod]
    public static void SaveContent(string content, bool autosave)
    {
        if (autosave)
        {
            HttpContext.Current.Session["UserContent"] = content + "Ajax hit";
        }
        else
        {
            // TODO save data to a database
            HttpContext.Current.Session["UserContent"] = String.Empty;
        }
    }

No comments:

Post a Comment