0

I want to call asp.net function from a javascript function passing string value.

this is the asp.net function :

[System.Web.Services.WebMethod]     
public static string InsertData(string ID)
{
    string source = "Data Source=(LocalDB)\v11.0;Integrated Security=True;Connect Timeout=30";
    using(SqlConnection con = new SqlConnection(source))
    {
        using (SqlCommand cmd = new SqlCommand("Insert into Book (Name) values(@Name)", con))       {
            con.Open();
            cmd.Parameters.AddWithValue("@Name", ID);
            cmd.ExecuteNonQuery();
            return "True";
        }
    }
}

So i want to call this function from javascript function which passes the string value "ID" to the the asp.net function.

this is the javascript function i use

 function CallMethod() {
            PageMethods.InsertData("hello", CallSuccess, CallError);

        }

        function CallSuccess(res) {
            alert(res);
        }

        function CallError() {
            alert('Errorrr');
        }

and i call it from here

<body>
        <header>        
        </header>       
        <div class="table"  id="div1" > </div>                      
        <form id="Form1" runat="server">
            <asp:Button id="b1" Text="Submit" runat="server" onclientclick="CallMethod();return false;"/>
            <asp:ScriptManager enablepagemethods="true" id="ScriptManager1" runat="server"></asp:ScriptManager>
        </form> 

    </body>

so i have a button and onClick i want to add "Hello" Row to my table but nothing happens and CallError function calls

2
  • You absolutely should verify that the given string input is in the correct format ie is not an attack payload before blindly inserting the contents into your database. This is an XSS attack vector waiting to happen. Commented Jul 1, 2014 at 13:56
  • im not even properly inserting the data into the table before doing security checks but thanks anyway Commented Jul 1, 2014 at 14:35

3 Answers 3

1

You can call web method from ajax call in javascript . you need to set url parameter values to function you want to call and you can pass value in the data prameter in json formate. like this data:"{ParamterName:'VALUE'}

 <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "YourPage.aspx/YouPageMethod",
                data: "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    alert('Method Called Sucess fully');
                },
                error: function (result) {
                    alert("error " + result);
                }
            });
        });
    </script>

OR

you can call using PageMethod Eample

 <script type="text/javascript">
        function callInsert() {
            PageMethods.InsertDate(id, OnSucceeded, OnFailed);
        }

        function OnSucceeded(response) {
            alert(response);
        }
        function OnFailed(error) {
            alert(error);
        }   


  /* call this javascript function */    
    callInsert();

</script>
Sign up to request clarification or add additional context in comments.

5 Comments

so this will call function("YouPageMethod") from` MyPage.aspx.cs` when document is ready ?In my case my asp.net function is called InsertData and its in WebForm1.aspx.cs
function CallMethod() { PageMethods.InsertData("hello", CallSuccess, CallError); } function CallSuccess(res) { alert(res); } function CallError() { alert('Errorrr'); }
can you update code in your question. So other can also see it
and i call CallMethod() function from button click - onclientclick="CallMethod();"
onclientclick="CallMethod();return false;" add return false with function call other wise your page will post back
0

You will need to include Jquery first in your page. Then you need to add the following Javascript code.

 <script type="text/javascript">
  var id ="5";  //your id will be stored here
    $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: "YourPage.aspx/InsertData"  + "&?id="  ,
            data: "",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
                alert('Success');
            },
            error: function (xhr, request, status) {
                 alert(xhr.responseText);
            }
        });
    });
</script>

1 Comment

ok so i think it works both ways with Jquery and with PageMethod. The thing is that it gives me failure message both ways and i dont know why. The asp.net function seems properly constructed
0

You need to have scriptManager in your .aspx page

    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />

After that you can call the method using

    <script type="text/javascript">
    function func(){
    PageMethods.InsertData(id,success_msg,failure_msg);
    }
    </script>

1 Comment

well i have everything i need and same story no rows added in the table

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.