Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting jQuery Ajax return data in Asp.Net

I'm a newbie in jQuery and don't understand how in jQuery Ajax returns data. I have some simple function to get some data like below

[WebMethod(EnableSession = false)]
protected int SignIn()
{
    return 0;
}

and in my .aspx page I have this

$(document).ready(function () {
        $("#si").click(function 
            () {
            $.ajax({
                type: "POST",
                url: "SignIn.aspx/SignIn",
                contentType: "application/json",
                success: function (txt) {
                    alert(txt);
                }
            });
        });
    });

but in alert I get the whole SignIn.aspx (all html tags and so on). how to alert the 0 which the SignIn() returns?thanks

like image 910
ePezhman Avatar asked Feb 02 '26 15:02

ePezhman


2 Answers

Make the SignIn method static and public and show alert with following code: alert(txt.d);

like image 173
Yuriy Rozhovetskiy Avatar answered Feb 05 '26 07:02

Yuriy Rozhovetskiy


You are asking an ASPX file for data and I think that should be an ASMX.

Check out Dave Ward's post where I leaned about all this: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/

The simplest example I could make looks like this:

Add a Web Service (ASMX) containing

using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
   [WebMethod]
   public int Status(int input) {
      return input + 1;
   }
}

Then in your HTML do

<html>
<head>
    <title>Test</title>
    <script src="jquery-1.6.2.min.js" ></script>
</head>
<body>
<script>
  $(function () {
    $.ajax({
      url: 'WebService.asmx/Status',
      data: '{ input: 0 }',
      type: 'POST',
      dataType: 'json',
      contentType: 'application/json',
      success: function (data, status) {
        alert(data);
        alert(typeof data);
      }
    });
  });
</script>
</body>
</html>

In the ajax call the string defined in data is the input to the web method. Names must match. In the success callback, the first alert shows the value returned (input plus one) and the second alert shows that it is a number, not a string. Because the datatype is set to JSON, the web method returns JSON allowing the data to be typed correctly.

Hope this helps.

like image 34
nickd Avatar answered Feb 05 '26 06:02

nickd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!