Sarath Kumar
Sarath Kumar

Reputation: 1146

jQuery, ajax POST method success returns: Undefined

my script code:

$('#btnSave').click(function() {
    var pageUrl = '<%= ResolveUrl("~/TestPage.aspx/SystemEdit")%>';
    var ip = $('#editIP').text();
    var loc = $('#txtBay').val();
    var team = $('#txtTeam').val();
    var port = $('#txtPort').val();
    var xcel = "", office = "", moni = "";                                   
    var parameter={ "ip": ip, "loc": loc, "team": team, "port": port, "excel": xcel, "office": office, "monitor": moni}

    $.ajax({
        type: 'POST',
        url: pageUrl,
        data: JSON.stringify(parameter),
        contentType: 'json',
        success: function(data) {
            alert(data);
        },
        error: function(data,success,error) {
            alert("Error:" +error);
        }
    });           
});

my code behind c# code is:

[WebMethod]
public static string SystemEdit(string ip, string loc,string team, string port, string excel,string office, string monitor)
{
    return "The Current Time is: "+ DateTime.Now.ToString();
}

my page name is : TestPage.aspx

While clicking the save button I'm getting 'undefined'. I'm not getting the current time from code behind c#.

Upvotes: 4

Views: 2912

Answers (3)

Akshay Shetty
Akshay Shetty

Reputation: 1

If you are using vs2013 then make sure you disable the below line in route.config to get things working.

 'settings.AutoRedirectMode = RedirectMode.Permanent

My VB Code Behind:

  <WebMethod()>


       Public Shared Function GetReport(ByVal Data As String) As String
          Try

                Return "Hello" + Data

            Catch ex As Exception

                Return "Failed"
      End Try
End Function

Js Script :

$('#btnSave').click(function () {
  var char = $(this).text();

 var SendData = {};
  $.ajax({
      type: "POST",
      url: "TEST.aspx/GetReport",
      data: JSON.stringify(SendData),
      data: "{ 'Data': '" + char + "'}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (data) {
          $('#lbl_test').text(data.d);
      },
      error: function (data, success, error) {
          alert("Error:" + error);
      }
  });
 });

Upvotes: 0

Neel
Neel

Reputation: 11731

You need to return json result as below:

return JsonConvert.SerializeObject("The Current Time is: "+ DateTime.Now.ToString());

also put below attribute above method:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

And as you specified json format you should write:

 contentType: "application/json; charset=utf-8",

By the way you should use a Webservice here!

Upvotes: 1

Jai
Jai

Reputation: 74738

I guess setting a json content type should be done this way:

contentType: 'application/json',

Upvotes: 0

Related Questions