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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

@rydice-First thanks for your reply.Even If I remove content type it I'm unable to receive it.
remove 'type', so that jquery sends the parameter in the querystring, the default is 'GET'
@ryudice-Did with that too but no success.
Change the $("#Result").text(msg.d); to $("#Result").html(msg.d);
0

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

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

1 Comment

@valeklosse-From this question stackoverflow.com/questions/2604874/… the same issue stated that not to mention the quotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.