-1

I am new to jquery. I often do my coding in c# and Now i have to work with jquery. I Know basic of jquery. Just few functions of jquery. But now I want to do some advance thing . I want to save update delete the data in sql server from my asp.net page using jquery. I tried a jquery code for this but it is not working. I am not able to get what is the error and where i am going wrong. Here is my code of jquery which i am using

<script type="text/javascript">
        $(document).ready(function () {
            $("#Button1").click(function () {
                $.ajax({
                    type: 'POST',
                    contentType: "application/json;charset=utf-8",
                    url: 'Default2.aspx/InsertMethod',
                    data: "{'username':'" + document.getElementById('txtusername').value + "','password':'" + document.getElementById("txtpassword").value + "'}",
                    async: false,
                    success: function (response) {
                        $('#txtusername').val('');
                        $('#txtpassword').val('');
                        alert("record has been saved in database");

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

                });

            });

        });

I create a web method in c# code where i write the code for save data in sql server and calling that web method in jquery. But this code is not working Here is my C# code

 [WebMethod]
    public static string InsertMethod(string username, string password)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
        con.Open();
        SqlCommand cmd = new SqlCommand("insert jquerydata values('" + username + "','" + password + "'", con);
        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();
        cmd.Dispose();
        con.Close();
        return "true";

    }

Please tell me how can I do it.

18
  • 1
    i guess your code is quiet ok .. are you getting any error in javascript console ?? Commented Oct 23, 2013 at 12:49
  • 1
    What do you mean by 'not working'? Nothing happens? Do you have any errors in console? Try to put a breakpoint in your method to see if it is being called. Commented Oct 23, 2013 at 12:50
  • 1
    @Polaris878 see i am totaly new in jqeury i dnt know anything about it please tell me how to see the error and and what i have to Commented Oct 23, 2013 at 12:53
  • 1
    Turns out you can do that this question inlcudes an article and some examples. Commented Oct 23, 2013 at 12:58
  • 1
    I did check line number 7. And I told you there is an error in that line and provided you with the fix. Time for you to check your own code now. Commented Oct 23, 2013 at 13:17

3 Answers 3

0

Your Jquery seems to be fine. Just make sure your method is invoked. You can add a break point and debug your c# method.

In your c# code

SqlCommand cmd = new SqlCommand("insert jquerydata values('" + username + "','" + password + "'", con);

I guess you are missing 'into' keyword.

You can also debug your jquery using the 'debugger' keyword and make sure you uncheck disable script debugging option in the IE-->Internet Options-->Advance-->under Browsing.

Sign up to request clarification or add additional context in comments.

Comments

0

I have tested this and it works:

Default2.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default2.aspx.cs" Inherits="SO19542105.Default2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>SO19542105: how to save data in database using jquery</title>
    <script type="text/javascript" src="Scripts/jquery-1.8.2.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#Button1").click(function () {
                $.ajax({
                    type: "POST",
                    contentType: "application/json;charset=utf-8",
                    url: "Default2.aspx/InsertMethod",
                    data: "{'username':'" + $("#txtusername").val() + "', 'password':'" + $("#txtpassword").val() + "'}",
                    async: false,
                    success: function (response) {
                        $("#txtusername").val("");
                        $("#txtpassword").val("");
                        alert("record has been saved in database");
                    },
                    error: function () {
                        console.log("there is some error");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <input type="text" id="txtusername" placeholder="username" />
    <input type="password" id="txtpassword" placeholder="password" />
    <input type="button" id="Button1" value="OK" />
</body>
</html>

Default2.aspx.cs

using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Services;

namespace SO19542105
{
    public partial class Default2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static string InsertMethod(string username, string password)
        {
            using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString))
            using (var cmd = con.CreateCommand())
            {
                cmd.CommandText = "INSERT INTO jquerydata(username, password) VALUES(@username, @password)";
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Parameters.AddWithValue("@username", username);
                cmd.Parameters.AddWithValue("@password", password);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
            return "true";
        }
    }
}

2 Comments

I try this but its give me this error in console HTTP/1.1 500 Internal Server Error
Did you debug through the code at all to see what exact error you're getting? Could be as simple as a bad connection string.
0
Write Static method in C# i.e. in aspx.cs page to insert data

[WebMethod]
    public static void AddRecord(string username, string password)
    {
        //SIMPLE SQL QUERY INSERT INTO
        {
            using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString))
            using (var cmd = con.CreateCommand())
            {
                cmd.CommandText = "INSERT INTO jquerydata(username, password) VALUES(@username, @password)";
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Parameters.AddWithValue("@username", username);
                cmd.Parameters.AddWithValue("@password", password);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
            return "true";
        }
        }
    }



create a html to accept two fields and insert data on click of button

<script src="3.2.1/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript">

    $(document).ready(function () {

        $("#Button1").on('click', function (e) {


            var userDetails = {
            username:$('#txtusername').val(),
            password: $('#txtpassword').val()
            };

            $.ajax({
                type: "POST",
                url: "pagename.aspx/AddRecord",
                data: JSON.stringify(userDetails),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                error: OnErrorCall
            });

            function OnSuccess(response) {
                var result = response.d;
                if (result == "success") {
                    $("#msg").html("New record addded successfully  :)").css("color", "green");
                }

            }

            function OnErrorCall(response) {
                $("#msg").html("Error occurs  :(").css("color", "red");
            }

        });

    });

</script>



<form id="form1">
    <div id="Tree">
       <input type="text" id="txtusername" placeholder="username" />
    <input type="password" id="txtpassword" placeholder="password" />
    <input type="button" id="Button1" value="OK" />
    </div>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.