Wednesday, 18 September 2013

Insert Data In SQL Data Base using Jquery in Asp.Net

To make you understand take a small example. Suppose we want to make a simple signup form (in which we will not check similar username or duplicate user name; I hope you can easily do it). So make a table with two columns 'UserID' and 'Password'.
Take three text box one for username and other two to match and insert password (You can use java script to match password; I am not including it here). A button which will insert data in data base after clicking it.
Write this code after closing form tag and just above closing of body tag.
<script type="text/javascript">
        $(document).ready(function () {
            $("#Button1").click(function () {
                    type: 'post',
                    contentType: "application/json; charset=utf-8",
                    url: 'datainsertunsingjquery.aspx/InsertMethod',

              // Here InsertMethod is a function on page name datainsertusingjquery.aspx                  
             data: "{'UserID':'" + document.getElementById('TextBox1').value + "', 'Password':'" + document.getElementById('TextBox2').value + "'}",
                    async: false,
                    success: function (response) {
                        alert("Record Has been Saved in Database");
                    error: function ()

                    { console.log('there is some error'); }



And in the page of 'datainserusingjquery.aspx' write this function 'InsertMethod()'
    public static string InsertMethod(string UserID, string Password)
        SqlConnection con = new SqlConnection("Pass here your Data base connection string");
        SqlCommand cmd = new SqlCommand("Insert into Login values('" + UserID + "', '" + Password + "')", con);
        return "True";