Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
hiiii , i am begginer in jquery.ajax , i try to get a scalar value from DB but it alert undefined , i don't know why . below is HTML page

HTML
<script src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#btn1').click(function () {
            $.ajax({
                type: "POST",
                url: "WebForm1.aspx/getdep",
                data: '{x:1}',
                datatype: "json",
                contentType: "application/json charset-utf-8",
                success: function (data) {
                    alert(data.d);
                },
            });
        });
    });
</script>

below is .cs page

C#
public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [webmethod]
    public string getdep(int x)
    {
        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString))
        {

            SqlCommand cmd = new SqlCommand("select depname from dep where depid="+x, connection);
            connection.Open();
            string result = cmd.ExecuteScalar().ToString();
            return result;
        }
    }
}
Posted
Comments
ZurdoDev 17-Sep-14 11:18am    
Debug it and you should find quickly what is happening.
Hercal 17-Sep-14 11:28am    
how :D ?
ZurdoDev 17-Sep-14 11:54am    
Put a breakpoint.
Hercal 17-Sep-14 12:11pm    
i know , but i mean how to debug [ client side code ]

1 solution

ExecuteScalar() is of type object:
see here[^]
so:
C#
[webmethod]
    public object getdep(int x)
    {
        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString))
        {

            SqlCommand cmd = new SqlCommand("select depname from dep where depid="+x, connection);
            connection.Open();
            var result = cmd.ExecuteScalar();
            return result;
        }
    }
 
Share this answer
 
Comments
Hercal 17-Sep-14 11:28am    
but i parse it into string :- string result = cmd.ExecuteScalar().ToString();
Herman<T>.Instance 17-Sep-14 16:40pm    
you call:
string theAnswer = getdep(<yourint>).ToString();
ZurdoDev 17-Sep-14 11:55am    
No. He wants to return a string. ExecuteScalar().ToString() will work.
Hercal 17-Sep-14 12:10pm    
i try it , it doesn't work , it also alert undefined ,...........be noted that when i execute the same code in page load using ExecuteScalar().ToString() and without jquery.ajax , it works.

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