locked
Calling WebMethod using AJAX RRS feed

  • Question

  • User256094225 posted


    I'm trying to insert data to mysql without postbacks using ajax.

    the following code for that is

    <script src="Scripts/jquery-3.5.1.min.js"></script>
    <script src="Scripts/jquery-3.5.1.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <input type="button" value="Submit" onclick="SaveRecord();" />

    <script type="text/javascript">
    function SaveRecord() { var obj = { Year: $("#yeartxt").val(), Title: $("#titletxt").val(), Content: $("#contenttxt").val() }; //Jquery Ajax call to server side method $.ajax({ type: "POST", url: "Page.aspx/InsertDetails", data: JSON.stringify(obj), contentType: "application/json; charset=utf-8", dataType:"json", success: function (data) { alert("Updated!"); } }); } </script>

    The server side code (WebMethod) is

            [WebMethod]
            public static void InsertDetails(string Year, string Title, string Content)
            {
                string CoString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
                using (MySqlConnection CoN = new MySqlConnection(CoString))
                {
                    using (MySqlCommand cmd = new MySqlCommand("INSERT INTO db(year, title, content) VALUES(@year, @title, @content)", CoN))
                    {
                        CoN.Open();
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@Name", Year);
                        cmd.Parameters.AddWithValue("@Salary", Title);
                        cmd.Parameters.AddWithValue("@DeptId", Content);
                        cmd.ExecuteNonQuery();
                    }
                }
            }

    However, the WebMethod is not being called (I tried debugging it). I tried playing around the code. Nothing worked. The alert in "success: function (data) { alert("Updated!"); }" is working, this probably indicates that there's nothing wrong with the ajax code, I suppose.

    I need help with that, or an alternative for inserting data to mysql without a postback. That is my focus.

    Thank you.

    Monday, November 23, 2020 8:24 PM

Answers

  • User-939850651 posted

    Hi amir1507,

    Have you carefully checked what I explained above? Your current problem is because of the wrong data structure.

    If you need to pass an object, please use the entity of the corresponding structure to receive the parameter:

    Please refer to code below:

    <head runat="server">
        <title></title>
        <script src="Scripts/jquery-3.5.1.min.js"></script>
        <script type="text/javascript">  
    
            function SaveRecord() {
                var obj = {
                year : $("#yeartxt").val(),
                title : $("#titletxt").val(),
                content : $("#contenttxt").val()
                };
                //Jquery Ajax call to server side method  
                $.ajax({
                    type: "POST",
                    url: "TestPage.aspx/InsertDetails",
                    data: JSON.stringify({ 'detail': obj }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        alert("Updated!");
                    }
                });
            }
        </script>
       
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
              year: 
                <asp:TextBox runat="server" ID="yeartxt"></asp:TextBox>
                <br />
                title: 
                <asp:TextBox runat="server" ID="titletxt"></asp:TextBox>
                <br />
                content: 
                <asp:TextBox runat="server" ID="contenttxt"></asp:TextBox>
                <br />
                <input type="button" value="Submit" onclick="SaveRecord();" />
            </div>
        </form>
    </body>
    public class Detail
        {
            public string year { get; set; }
            public string title { get; set; }
            public string content { get; set; }
        }
    [WebMethod]
            public static void InsertDetails(Detail detail)
            {
                string CoString = ConfigurationManager.ConnectionStrings["conStr"].ToString();
                using (MySqlConnection CoN = new MySqlConnection(CoString))
                {
                    using (MySqlCommand cmd = new MySqlCommand("INSERT INTO db (year, title, content) VALUES (@year, @title, @content)", CoN))
                    {
                        CoN.Open();
    //If you specify the SQL statement that needs to be executed, you do not need to use a stored procedure. //cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@year", detail.year); cmd.Parameters.AddWithValue("@title", detail.title); cmd.Parameters.AddWithValue("@content", detail.content); cmd.ExecuteNonQuery(); } } }

    Hope this can help you.

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 25, 2020 2:07 AM

All replies

  • User-939850651 posted

    Hi amir1507,

    It is feasible to use ajax to call functions in code behind. Your current problem has the following three points:

    1. If you need to use a stored procedure to implement record insertion, then the parameter of the SqlCommand object, you need to add the name of the stored procedure instead of the SQL statement.

    using (MySqlCommand cmd = new MySqlCommand("INSERT INTO db(year, title, content) VALUES(@year, @title, @content)", CoN))
                    {
                        CoN.Open();
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;

    2. If you pass sql parameters, please use the correct parameter name:

    using (MySqlCommand cmd = new MySqlCommand("INSERT INTO db(year, title, content) VALUES(@year, @title, @content)", CoN))
                    {
                        CoN.Open();
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@Name", Year);
                        cmd.Parameters.AddWithValue("@Salary", Title);
                        cmd.Parameters.AddWithValue("@DeptId", Content);
                        cmd.ExecuteNonQuery();
                    }

    3. When using ajax to pass parameters to background functions, please use the correct structure:

    var obj = { Year: $("#yeartxt").val(), Title: $("#titletxt").val(), Content: $("#contenttxt").val() };
    $.ajax({
                type: "POST",
                url: "Page.aspx/InsertDetails",
                data: JSON.stringify(obj),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    alert("Updated!");
                }
            });

            public static void InsertDetails(string Year, string Title, string Content)

    You passed an object and used three variables to receive, so the problem occurred.

    You could try something like this:

    var year = $("#yeartxt").val();
    var title = $("#titletxt").val();
    var content = $("#contenttxt").val();
    
    $.ajax({
        type: "POST",
        url: "TestPage.aspx/InsertDetails",
        data: "{'Year':" + year + ",'Title':" + title + ",'Content':" + content + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
           alert("Updated!");
       }
    });

    [WebMethod]
    public static void InsertDetails(string Year, string Title, string Content)

    Or you could define custom class for it:

    var obj = {
                year : $("#yeartxt").val(),
                title : $("#titletxt").val(),
                content : $("#contenttxt").val()
                };
                //Jquery Ajax call to server side method  
                $.ajax({
                    type: "POST",
                    url: "TestPage.aspx/InsertDetails",
                    //data: JSON.stringify(obj),
                  data: JSON.stringify({ 'detail': obj }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        alert("Updated!");
                    }
                });

    public class Detail { public string year { get; set; } public string title { get; set; } public string content { get; set; } }

    [WebMthod]
    public static void InsertDetails(dynamic detail)

    Hope this can help you.

    Best regards,

    Xudong Peng

    Tuesday, November 24, 2020 9:20 AM
  • User256094225 posted

    thank you for your response,

    it did not work.

    The server side code is not being called.

    Tuesday, November 24, 2020 9:47 AM
  • User256094225 posted

    I checked the error on the network tab in dev tools.

    it first gave me the following error:

    {Message: "Authentication failed.", StackTrace: null,…} ExceptionType: "System.InvalidOperationException"

    I changed the Redirect Mode in Route config to

     settings.AutoRedirectMode = RedirectMode.Off;

    and then debugged once again to get this new error

    {Message: "Invalid JSON primitive: undefined.",…}
    
    ExceptionType: "System.ArgumentException"
    Message: "Invalid JSON primitive: undefined."
    StackTrace: " at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() ↵ at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) ↵ at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth) ↵ at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) ↵ at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer) ↵ at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) ↵ at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input) ↵ at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer) ↵ at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context) ↵ at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)"

    Tuesday, November 24, 2020 10:04 AM
  • User-939850651 posted

    Hi amir1507,

    Have you carefully checked what I explained above? Your current problem is because of the wrong data structure.

    If you need to pass an object, please use the entity of the corresponding structure to receive the parameter:

    Please refer to code below:

    <head runat="server">
        <title></title>
        <script src="Scripts/jquery-3.5.1.min.js"></script>
        <script type="text/javascript">  
    
            function SaveRecord() {
                var obj = {
                year : $("#yeartxt").val(),
                title : $("#titletxt").val(),
                content : $("#contenttxt").val()
                };
                //Jquery Ajax call to server side method  
                $.ajax({
                    type: "POST",
                    url: "TestPage.aspx/InsertDetails",
                    data: JSON.stringify({ 'detail': obj }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        alert("Updated!");
                    }
                });
            }
        </script>
       
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
              year: 
                <asp:TextBox runat="server" ID="yeartxt"></asp:TextBox>
                <br />
                title: 
                <asp:TextBox runat="server" ID="titletxt"></asp:TextBox>
                <br />
                content: 
                <asp:TextBox runat="server" ID="contenttxt"></asp:TextBox>
                <br />
                <input type="button" value="Submit" onclick="SaveRecord();" />
            </div>
        </form>
    </body>
    public class Detail
        {
            public string year { get; set; }
            public string title { get; set; }
            public string content { get; set; }
        }
    [WebMethod]
            public static void InsertDetails(Detail detail)
            {
                string CoString = ConfigurationManager.ConnectionStrings["conStr"].ToString();
                using (MySqlConnection CoN = new MySqlConnection(CoString))
                {
                    using (MySqlCommand cmd = new MySqlCommand("INSERT INTO db (year, title, content) VALUES (@year, @title, @content)", CoN))
                    {
                        CoN.Open();
    //If you specify the SQL statement that needs to be executed, you do not need to use a stored procedure. //cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@year", detail.year); cmd.Parameters.AddWithValue("@title", detail.title); cmd.Parameters.AddWithValue("@content", detail.content); cmd.ExecuteNonQuery(); } } }

    Hope this can help you.

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 25, 2020 2:07 AM