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 () {
                $.ajax({
                    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) {
                        $('#TextBox1').val('');
                        $('#TextBox2').val('');
                        alert("Record Has been Saved in Database");
                    },
                    error: function ()

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

                });
                    });

                         });
   
   
    </script>

And in the page of 'datainserusingjquery.aspx' write this function 'InsertMethod()'
[WebMethod]
    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);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        return "True";
    }

Comments

Popular posts from this blog

DTS package conversion in SSIS to use in SQL 2012 and SQL 2016

Add Custom Tags in Web config file in ASP .Net

Infinite Scroll in Asp.Net C# using Javascript without Third party Plugin