Click here to Skip to main content
15,885,435 members
Please Sign up or sign in to vote.
2.00/5 (3 votes)
See more:
hi,

i am new to JSON n jquery. i make a simple application for insert of data but it not work. i any have experiece in this please help.


currently data is not inserted to database

webservice
------------

C#
public class WebService : System.Web.Services.WebService {

    public WebService ()
    {
        //InitializeComponent();
    }
    string conStr = WebConfigurationManager.ConnectionStrings["testconn"].ConnectionString;
    int rowsInserted = 0;

    [WebMethod]
    public string InsertWebservice(int id, string name, string address)
    {
        using (SqlConnection conn = new SqlConnection(conStr))
        {
            string sql = string.Format(@"INSERT INTO [TestDB].[dbo].[emp] ([id],[name],[Address]) VALUES ('{0}','{1}','{2}')", id, name, address);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = sql;
            cmd.CommandType = CommandType.Text;
            conn.Open();
            rowsInserted = cmd.ExecuteNonQuery();
            conn.Close();
            cmd = null;
        }
        return string.Format("Thank you, {0} number of rows inserted!", rowsInserted);

    }

-------------
at aspx page
-------------
XML
<table>
   <tr><td>  Id:</td><td><asp:TextBox ID="_id" runat="server"></asp:TextBox></td></tr>
    <tr><td>Name:</td><td><asp:TextBox ID="_txtname" runat="server"></asp:TextBox></td></tr>
    <tr><td>Address:</td><td><asp:TextBox ID="_addr" runat="server"></asp:TextBox></td></tr>

   </table>

  <asp:Button ID="Button1" runat="server" Text="Button"  OnClientClick="CallService();"
              />

 <script type="text/javascript">

       $(insert);
       function insert() {
           $('#Button1').click(CallService);
       }
       
       function CallService() {
         
           var id = $('#_id').val();
           var name = $('#_txtname').val();
           var addr = $('#_addr').val();
           $.ajax({
               type: "POST",
         
       url: "WebService.asmx/InsertWebservice",   
               
               contentType: "application/json;charset=utf-8",
               dataType: "json",                         

               //  data: "{ 'id': '" + id + "','name': '" + name + "', 'address':'" + addr + "'}",
               data: JSON.stringify({ id: 'id', name: 'name', address: 'address' }),
               async: false,
               success: function (data) {
                   $('#message').text(data.d);
               }
           });
       }
        </script>   
Posted
Updated 24-Feb-16 1:35am
v3
Comments
ZurdoDev 10-Jan-13 8:04am    
If you put breakpoints in your code, what IS happening?

1 solution

Here's what we need to know:

1 - does the success message get shown ?
2 - does the back end method get called ?
3 - is there a reason you need to use a webservice and not just an AJAX call ?
4 - have you debugged this in Chrome to see what happens when it runs ? Are there any javascript errors ?

I never use stringify, I just use an array of name/value pairs. Well, I've used stringify to serialise an entire form, that's about it. In fact, while I break it out, the line you commented out looks more like what I usually do. Here is an example of how I'd make an AJAX call:

JavaScript
var postData = {
    urlIntegrated: urlIntegrated,
    id: id,
    password: $.trim($("#Password").val()),
    secretQuestion: $("#SecretQuestionId").val(),
    secretAnswer: $.trim($("#SecretAnswer").val())
};

$.post("/Home/StoreProfile", postData, function (data)
{
    if (data.Saved)
    {
        jAlert("Profile Saved", "Success", function () {
            window.location = "/";
        });
    }
    else
    {
        jAlert("Profile save failed, please try again or contact our support.", "Error");
    }


}, 'json');


I am posting to an ASP.NET MVC website. I am not sure if a web service will populate the values in the same way, but the way you wrote your method, is how it works fine for me in my site.

Just to add, building your SQL the way you are, anyone who wants to erase your DB, can. Read up on SQL injection attacks. You need to create paramaterized queries, or call stored procs.
 
Share this answer
 
Comments
Member 9013369 14-Aug-13 2:29am    
How to insert data into sql server datatable using jquery
Christian Graus 14-Aug-13 20:09pm    
You can't. jquery itself runs on the client. You can use it to make an AJAX call that does that, though.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900