Amit Sinha
Amit Sinha

Reputation: 614

Ajax using JQuery in ASP .NET c#

I am trying to use JQuery ajax in asp .net c#. The code I am using is ...

HTML FORM:

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

JQuery Part :

<script type="text/javascript">
    function ShowCurrentTime() {
        //alert(window.location.pathname);
        $.ajax({
            type: "POST",
            url: "Display.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>

CS PArt:

    using System.Web.Services;

    This part below is under partial class which inherits from Page class.

   [WebMethod]

    public static string GetCurrentTime(string name)
    {

     return "Hello "+ name +"! " + Environment.NewLine + "The Current Time is: "
            + DateTime.Now.ToString();
    }

Problem: It is not working. Please let me know if I am missing any setting or any name space. Or any thing. URL I Put in ajax Call is correct as I verified it by var pathname = window.location.pathname; I supplied data also while calling ajax.

Upvotes: 2

Views: 4335

Answers (3)

majita
majita

Reputation: 1326

Maybe changing

 failure: function (response) {
        alert(response.d);
    }

to

 error: function (response) {
        alert(response.d);
    }

Will help find the issue. I don't see a failure callback in the docs - http://api.jquery.com/jquery.ajax/

Upvotes: 3

Tony Dong
Tony Dong

Reputation: 3313

JQuery has some error

    $("#< %=txtUserName.ClientID%>")[0].value

need to be

    $("#<%=txtUserName.ClientID%>")[0].value

or

    $("#<%=txtUserName.ClientID%>").val() 

Upvotes: 0

Chris Bergin
Chris Bergin

Reputation: 415

The things I can see right off the bat:

  1. $.ajax doesn't take a "failure" parameter, but rather "error." Even then, you should be using .done() and .fail() instead (see http://api.jquery.com/jQuery.ajax/)
  2. Your error handling function will be triggered when your page method throws an exception. The first parameter is a jqXHR object, not a JSON response from .NET (see the same link as from #1).
  3. Your page method should not go UNDER the page class, but within it.

Upvotes: 2

Related Questions