How do I call a server side method (ASP.NET/VB) using jQuery?

I'm trying to implement a simple server side call using jQuery, but it keeps returning 'undefined'
Here's my HTML

<head>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type = "text/javascript">
    function ShowCurrentTime() {
        $.ajax({
            type: "POST",
            url: "create.aspx/GetCurrentTime",
            data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            }
        });
    }
    function OnSuccess(response) {
        alert(response.d);
    }
</script>
</head>

Open in new window


and...

<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
    onclick = "ShowCurrentTime()" />
</div>

Open in new window


Here's my code behind...
    <System.Web.Services.WebMethod()> _
    Public Shared Function GetCurrentTime(ByVal name As String) As String
        Return "Hello " & name & Environment.NewLine & "The Current Time is: " & _
                 DateTime.Now.ToString()
    End Function

Open in new window


Anything obvious that I'm missing?
Mike MillerSoftware EngineerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Najam UddinCommented:
alert(response.responseText);
Mike MillerSoftware EngineerAuthor Commented:
undefined
Chris StanyonWebDevCommented:
The response from your werbservice is just plain text, not JSON, so remove the dataType argument from your jQuery script, and then just alert the response:

alert(response);

Also remove the contentType argument from your script - you're not sending JSON to the server, so there's no need for it
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

dejaanbuCommented:
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',

what is the need for [0] here?. that line should be...
data: '{name: "' + $("#<%=txtUserName.ClientID%>").val() + '" }',

Open in new window

Chris StanyonWebDevCommented:
@dejaanbu - it's to get the native DOM element from the jQuery object.

It's the equivalent to:

$('#txtUserName').val()
Mike MillerSoftware EngineerAuthor Commented:
When I replace with

alert(response);

and remove the content type line, nothing happens. I put the content line back in and left
alert(response);

and it returned

[object Object]
Mike MillerSoftware EngineerAuthor Commented:
When changing the line to

data: '{name: "' + $("#<%=txtUserName.ClientID%>").val() + '" }',

still returns undefined.
Mike MillerSoftware EngineerAuthor Commented:
Just for reference, I thought I'd add my full code and details. I'm using VS2013, testing mainly with IE11 but have also tried Chrome 46.0.2

My html side:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type = "text/javascript">
    function ShowCurrentTime() {
        $.ajax({
            type: "POST",
            url: "create.aspx/GetCurrentTime",
            data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.responseText);
            }
        });
    }
    function OnSuccess(response) {
        alert(response.responseText);
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
    onclick = "ShowCurrentTime()" />
</div>
    </div>
    </form>
</body>
</html>

Open in new window



And my code behind:

Public Class test
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub
    <System.Web.Services.WebMethod()> _
    Public Shared Function GetCurrentTime(ByVal name As String) As String
        Return "Hello " & name & Environment.NewLine & "The Current Time is: " & _
                 DateTime.Now.ToString()
    End Function
End Class

Open in new window

Chris StanyonWebDevCommented:
AS per my previous comment:

This line:

dataType: "json"

is telling your jQuery script that you are expecting back a JSON object, so it 'thinks' that response is an object, which is why you get [object Object] when you alert.

The fact is that your ASP script is not returning an object - it's just returning a string, so you need to tell your jQuery script that - that's why you need to remove that line. Here's what the code should look like:

function ShowCurrentTime() {
	$.ajax({
		type: "POST",
		url: "create.aspx/GetCurrentTime",
		data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
		contentType: "application/json; charset=utf-8",
		success: OnSuccess,
		failure: function (response) {
		    alert(response);
	    }
	});
};

function OnSuccess(response) {
	alert(response);
}

Open in new window

Mike MillerSoftware EngineerAuthor Commented:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type = "text/javascript">
    function ShowCurrentTime() {
        $.ajax({
            type: "POST",
            url: "create.aspx/GetCurrentTime",
            data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
            contentType: "application/json; charset=utf-8",
            success: OnSuccess,
            failure: function (response) {
                alert(response);
            }
        });
    };

    function OnSuccess(response) {
        alert(response);
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
    onclick = "ShowCurrentTime()" />
</div>
    </div>
    </form>
</body>
</html>

Open in new window



and

Public Class test
    Inherits System.Web.UI.Page
    <System.Web.Services.WebMethod()> _
    Public Shared Function GetCurrentTime(ByVal name As String) As String
        Return "Hello " & name & Environment.NewLine & "The Current Time is: " & _
                 DateTime.Now.ToString()
    End Function
End Class

Open in new window


result
Chris StanyonWebDevCommented:
OK. We're only seeing part of the problem here. My guess is that the message you're getting is coming from the 'failure' function and not the 'success' function.

Time to debug. Firstly, forget about the actual server response. Let's just make sure you're AJAX call is working. In your failure method, just alert("Failure"); and in your success method, just alert ("Success");

The reason is that the data returned to failure and success is different. The response to failure is an object, the response to success is text. This will narrow down which method is generating the Alert
Mike MillerSoftware EngineerAuthor Commented:
Good idea. Ok I made the changes as seen here...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type = "text/javascript">
    function ShowCurrentTime() {
        $.ajax({
            type: "POST",
            url: "create.aspx/GetCurrentTime",
            data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
            contentType: "application/json; charset=utf-8",
            success: OnSuccess,
            failure: function (response) {
                alert("Failure");
            }
        });
    };

    function OnSuccess(response) {
        alert(response);
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
    onclick = "ShowCurrentTime()" />
</div>
    </div>
    </form>
</body>
</html>

Open in new window


This returns "Success"
Chris StanyonWebDevCommented:
I can't see where it's getting "Success" from. Your success method is still showing as alert(response). It should be reading:

function OnSuccess(response) {
        alert("Success");
}
Mike MillerSoftware EngineerAuthor Commented:
Sorry, I changed it before copying/pasting to see if it still returned object. Just ran this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type = "text/javascript">
    function ShowCurrentTime() {
        $.ajax({
            type: "POST",
            url: "create.aspx/GetCurrentTime",
            data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
            contentType: "application/json; charset=utf-8",
            success: OnSuccess,
            failure: function (response) {
                alert("Failure");
            }
        });
    };

    function OnSuccess(response) {
        alert("Success");
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
    onclick = "ShowCurrentTime()" />
</div>
    </div>
    </form>
</body>
</html>

Open in new window


Returned "Success"
Chris StanyonWebDevCommented:
OK. Excellent. Now, we want to output the server's response to the browser console so we can see what's going on - this is a fantastic tool for debugging.

Edit your success function, so that it looks like this

function OnSuccess(response) {
    console.log(response);
    alert("Success");
}

Then, open your page in Google Chrome and press the F12 Key - you should now see the developer tools at the bottom of your page. One of the tabs is called Console. Click that and then fill in and submit your form - you should see exactly what comes back from the Server. Post that response up
Mike MillerSoftware EngineerAuthor Commented:
Object {Message: "Authentication failed.", StackTrace: null, ExceptionType: "System.InvalidOperationException"}
Chris StanyonWebDevCommented:
OK. The problem is with your ASP script (Authentication failed), and not with jQuery. Make the following change to your ASP script, just to see if it's a problem with your method (I don't think it is)

Public Shared Function GetCurrentTime(ByVal name As String) As String
    Return "This is a test"
End Function

If you still get the same error, then there's not much more I can help you with. I don't use ASP, so I don't know how the Authentication layer works, and I don't know how your app is configured.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mike MillerSoftware EngineerAuthor Commented:
Ok I added

Imports System.Web.Services

to my code behind. Now when I run the same code in Chrome, I get the success message, but nothing in the Console. So I changed the success code back to

alert(response);

and received [object Object]
Mike MillerSoftware EngineerAuthor Commented:
Got it.

In RouteConfig.vb I had to change the AutoRedirectmode settings to

settings.AutoRedirectMode = RedirectMode.Off

Open in new window


then add a ScriptManager to my page

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

Open in new window


Original code works perfect...
Mike MillerSoftware EngineerAuthor Commented:
I've requested that this question be closed as follows:

Accepted answer: 0 points for mwmiller78's comment #a41235339

for the following reason:

Figured it out
Mike MillerSoftware EngineerAuthor Commented:
Chris StanyonWebDevCommented:
Although we didn't come to a full conclusion on this, the problem was figured out through a process of debugging, so to request a close to the question with 0 points being assigned is bad form. The original question asked why the script was generating an 'undefined' response and I've given the reason for that - the ASP script was incorrect. The OP should award points, even if it's not a grade A to indicate that valuable assistance was given.
Mike MillerSoftware EngineerAuthor Commented:
I have no objection to awarding full points and a grade A for this question. I did not realize it was bad form. For what it's worth, I started over from scratch and just googled for hours to find the strange solution to my issue. That said, Chris is correct...I didn't form my question specifically to find the missing or incorrect dynamics of the IDE setup. Anyway, as I said, I'm happy to make the change
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.