Save (Insert) record in database using jQuery Ajax in ASP.Net

ashish007
 
on Oct 03, 2021 11:00 PM
279 Views

How to record save in databse using ajax

below my code check in google crome console mode. no error show. but reocrd not save in database. pls check

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    $('[id*=btncoment]').on('click', function  () {
        var comment = $(this).closest('tr').find('.comment').val();
        var postid1 = $(this).closest('tr').find('[id*=hfpostid]').val();
        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            url: "Default12.aspx/SaveBookDetails",
            data: "{'comment':'" + comment + "', 'p_id':'" + postid1 +  "'}",
            success: function (response) {
                alert("Comment  has been added successfully.");
                window.location.reload();
            }
        });
    });
});
</script>

 

public static bool SaveBookDetails(string comment, string postid)
{
    bool status;
 
    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["fbookConnectionString"].ConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand("SP_SAVECOMMENT", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@CommentMessage", comment);
            cmd.Parameters.AddWithValue("@p_id", postid);
 
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            Int32 retVal = cmd.ExecuteNonQuery();
            if (retVal > 0)
            {
                status = true;
            }
            else
            {
                status = false;
            }
            return status;
        }
    }
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Oct 03, 2021 11:08 PM
ashish007 says:
data: "{'comment':'" + comment + "', 'p_id':'" + postid1 +  "'}",

Change with below code.

data: "{'comment':'" + comment + "', 'postid':'" + postid1 +  "'}",

You need to make sure the parameter name same in both WebMethod and Ajax data property.

In your case it was different postid and p_id.