0

I am trying to use the simple ajax script to webmethod as follows:

  <script type="text/javascript">
        $(document).ready(function () {
         $("#btnretreive").click(function () {
            $.ajax({
                 type: "POST",
                 url: "Default.aspx/Gettext",
                 data: {inputtext: $('#sometext').val()},
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 success: function(msg) {
                     $("#Result").text(msg.d);
                   }
             });
         });
     });
 </script>

And this is my webmethod:

 <WebMethod()> _
    Public Shared Function Gettext(ByVal inputtext As String) As String
           Return inputtext
    End Function

Here is my HTML part:

<input id="sometext" type="text" />
<input id="btnretreive" type="button" value="button" />
<div id="Result"></div>

Now my problem is I'm unable to send the input text and receive it back.Can anyone point out the mistake I'm doing here.

coder
  • 13,002
  • 31
  • 112
  • 214

3 Answers3

1

You need to use the ScriptMethod attribute in your Web Method in order to return Json.

<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>

More information: http://msdn.microsoft.com/en-us/library/system.web.script.services.scriptmethodattribute.aspx

Note: you must keep the WebMethod attribute too as shown in MSDN.

Also, you need to convert the Json object you're passing to the WebMethod to string, for example:

data: JSON.stringify({inputtext: $('#sometext').val()}),

Hope it helps.

Meryovi
  • 6,121
  • 5
  • 42
  • 65
0

Since you specified contentType as application JSON jQuery is probably posting the data as json, which asp.net doesnt recognize and therefore doesnt receive the parameter value, webmethods receive parameters in querystring, try removing the contentType, only leaving dataType, also try removing 'POST' as type

ryudice
  • 36,476
  • 32
  • 115
  • 163
0

From memory, I believe the data part needs to be in a string. so the line will be

data: '{inputtext : ' + $('#sometext').val() + '}',
Valeklosse
  • 1,017
  • 3
  • 19
  • 36
  • @valeklosse-From this question http://stackoverflow.com/questions/2604874/passing-input-text-value-to-ajax-call the same issue stated that not to mention the quotes. – coder Apr 22 '12 at 20:03