-1

I want to insert a record in the db using JavaScript in SQL server database.

I don't have much concern for the security as this app wont be exposed on the web, but is meant for internal use. My main issue is that, when user clicks a button, Then a record has to be created in the db, I want to do this in the client side java script itself. Can you please tell, if there is a way to do it, I have been exploring a lot.

Cris
  • 12,799
  • 5
  • 35
  • 50
user2256404
  • 115
  • 1
  • 13
  • 1
    You will have to make a request to the server and create the db-record using asp.net. However you can use Ajax to send the request so you don't need the full postback. – mboldt Feb 20 '14 at 09:46
  • you need to call server side code from JavaScript to achieve it – Cris Feb 20 '14 at 09:46
  • Use Ajax and make a request to server side method which actually does the insert operation. – Rohan Feb 20 '14 at 09:53
  • One Question Please, my controls are in htm files, since i am using web-parts and loading the .htm files, how can i use a ajax function inside the htm file, its not allowing me, do i have to add some reference? – user2256404 Feb 20 '14 at 10:18

1 Answers1

0

You have to do something like this

Java Script:

  $(document).ready(function () {
    $('#btnsubmit').click(function () {
     $.ajax({
      type: 'POST',
      contentType: "application/json; charset=utf-8",
      url: 'Test.aspx/AddRecord',
      data: {'name': $('#txtname').val()},
      async: false,
      success: function (response) {
      alert("Record saved successfully in database");
      },
      error: function () {
      alert("some problem in saving data");
      }
      });

     });
    });
  }
});

HTML

Test.aspx

    <html>
    <body>
    <form id="form1" runat="server">
    <div>
     <table>
     <tr>
     <td>
         Name
     </td>
     <td>
         <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
     </td>
     <td>
         &nbsp;
     </td>
     </tr>
  <tr>
  <td>
      &nbsp;
  </td>
  <td>
      <input type="button" id="btnsubmit" value="Submit" />
  </td>
  <td>
      &nbsp;
     </td>
 </tr>

        </table>
    </div>
    </form>
    </body>
    </html>

Code Behind:

Test.aspx.cs

    public static string AddRecord(string name)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
        try
        {
            SqlCommand cmd = new SqlCommand("Insert into Test values("+name+")", con);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            return "Success";
        }

        catch (Exception ex)
        {
            return "failure";
        }
    }
Cris
  • 12,799
  • 5
  • 35
  • 50
  • One Question Please, my controls are in htm files, since i am using web-parts and loading the .htm files, how can i use a ajax function inside the htm file, its not allowing me, do i have to add some reference? – user2256404 Feb 20 '14 at 10:16