Tuesday, July 6, 2010

ajax post to post data to server and get response using jQuery and JSON.

1. Create a page PageName.aspx, create a div on that:
    <div id="target_div_id">  

    </div>
2. Include the jQuery file.
3. call the following javascript function on any event:
function JsonPost(input1, input2, input3, input4) {

        URL = "PageName.aspx/WebMethodName";

    var options = {

        type: "POST",

        contentType: "application/json; charset=utf-8",

        dataType: "json",

        url: URL,

        data: '{input1:"' + input1 + '", input2:"' + input2 + '", input3:"' + input3 + '", input4:"' + input4 + '"}',

        success: function (msg) {

            if (msg.d == 'error')

                alert(msg.d);

            else {

                $('#target_div_id').append(msg.d);

            }

            HideLoader();

        },

        error: function (msg) {

            alert(msg.d);

        }

    };

    $.ajax(options);

}
4. Following web method will automatically called:


    /// <summary>

    /// Create a web method, input parameter must be same as the parameters in our web method.

    /// from here we will have to return the complete html(including html controls, their ids and classes)

    /// </summary>

    /// <param name="input1"></param>

    /// <param name="input2"></param>

    /// <param name="input3"></param>

    /// <param name="input4"></param>

    /// <returns></returns>

    [WebMethod]

    public static string WebMethodName(string input1, string input2, string input3, string input4)

    {

        try

        {

            int j = 10;//some number depending upon our requirement

            StringBuilder sbResult = new StringBuilder();

            for (int i = 0; i < j; i++)

            {

                sbResult.AppendLine("<!--any required html containing controls and ids-->");

            }

            return sbResult.ToString();

        }

        catch (Exception ex)

        {

            return ex.Message;

        }

    }

No comments:

Post a Comment