35

I'm trying to call a server side method from client side via jQuery. My code is as follows:

Server side:

    using System.Web.Services;
    [WebMethod()]
    //[ScriptMethod()]
    public static void SendMessage(string subject, string message, string messageId, string pupilId)
    {
        //Send message
    }

Client side:

$("#btnSendMessage").live("click", function(){
  var subject = $("#tbSubject").val();
  var message = $("#tbMessage").val();
  var messageId = $("#hdnMessageId").val();
  var pupilId = $("#hdnPupilId").val();

  $.ajax({
      type: "POST",
      url: "./MessagePopup.aspx/SendMessage",
      data: ("subject=" + subject + "&message=" + message + "&messageId=" + messageId + "&pupilId=" + pupilId),
      error: function(XMLHttpRequest, textStatus, errorThrown){
          alert(textStatus);
      },
      success: function(result){
         alert("success");
      }
   });
   return false;
});

I've added a break point on the server side SendMessage method, but it's never hitting it, but when I run the code the jQuery success method is called. What could be causing this?`

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fermin
  • 34,961
  • 21
  • 83
  • 129

5 Answers5

38

To call ASP.NET AJAX "ScriptServices" and page methods, you need to use the full $.ajax() syntax:

$.ajax({
  type: "POST",
  url: "MessagePopup.aspx/SendMessage",
  data: "{subject:'" + subject + "',message:'" + message + ",messageId:'" + messageId + "',pupilId:'" + pupilId +"'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something interesting here.
  }
});

See this post for details on why that's necessary: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

Edit: The extension doesn't change to .asmx but remains .aspx.

DDA
  • 991
  • 10
  • 28
Dave Ward
  • 59,815
  • 13
  • 117
  • 134
  • 4
    Got it working, only difference on this code is the url was MessagePopup.aspx, not asmx. Thanks guys. – Fermin May 20 '09 at 10:48
  • @Dave Ward: thanks so much for making examples that work right out of the box! – delliottg Jun 13 '13 at 15:04
  • Can you please provide some insights on my issue: http://stackoverflow.com/questions/41752213/why-is-asmx-giving-an-error-when-pulling-data-using-client-script. Thanks. Mine is an `.asmx` – Si8 Jan 20 '17 at 13:53
9

It looks like you're trying to make use of a page method.

Take a look here Page Methods in ASP.NET Ajax for help

Stephen Newman
  • 1,977
  • 14
  • 18
2
$.ajax({  
        type: "POST",  
        url: "MessagePopup.aspx/SendMessage",  
        data: "{subject:'" + subject + "',message:'" + message + ",messageId:'" + messageId + "',pupilId:'" + pupilId +"'}",  
        async: true,  
        cache: false,  
        contentType: "application/json; charset=utf-8",  
        dataType: "json",  
        success: function() {},  
        error:function (xhr, ajaxOptions, thrownError){ alert(thrownError); }  
     });

If this doesn't work...and gives "Syntax Error: syntax error"...then add this

<httpHandlers>
            <remove verb="*" path="*.asmx"/>
            <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
            <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
            <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35" validate="false"/>
        </httpHandlers>
        <httpModules>
            <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions,
Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </httpModules>

between </compilation> and </system.web> in your Web.Config file.

Hope this will help somebody because took me a while to figure that beside jquery function i have to add that in Web.Config.

Frank
  • 21
  • 1
2

You should use web service instead of regular aspx web page. Web pages has no support to call web methods, I believe your jQuery request loads the HTML page instead. I suggest you two things:

  1. Use Fiddler2 (with IE) or HttpFox (with Firefox) to debug AJAX requests and responses on client side.
  2. Use WCF web service on the server side. in this case you can use SvcConfigEditor and SvcTraceViewer to configure and debug web methods on the server side.
Artem Koshelev
  • 10,548
  • 4
  • 36
  • 68
  • Why do you say WCF rather than ASMX? – Fermin May 20 '09 at 10:23
  • WCF is now primary and recommended communication technology for .NET. It has a tons of capabilities over asmx web servives, better testability (Google for "Unit testing WCF services"). Strategically, WCF is a right choice to learn. Check this post for more about asmx vs WCF: http://social.msdn.microsoft.com/Forums/en-US/dotnetstocktradersampleapplication/thread/048d8a45-dad8-431f-886c-9aae78862285 – Artem Koshelev May 20 '09 at 10:51
  • Also, you can check Microsoft performance benchmarks: http://msdn.microsoft.com/en-us/library/bb310550.aspx – Artem Koshelev May 20 '09 at 10:56
1

Here is code that might work in your situation.

<script type="text/javascript">
    $(document).ready(function () {

        // Add the page method call as an onclick handler for the button.
        $("#btnSubmit").click(function () {

            //get the string from the textbox
            $.ajax({

                type: "POST",
                url: "testSearch.aspx/GetMyShippingDate",
                contentType: "application/json; charset=utf-8",
                data: "{'tracking_num': '" + $("#txtTrackingNumber").val() + "'}",  
                dataType: "json",
                success: function (date) {

                    // Replace the div's content with the page method's return.
                    Success(date);

                },
                error: Failed
            });
        });
    });

     function Success(result) {  
          $("#ParcelShippingDate").html(result.d);
      }  
      function Failed(result) {  
          alert(result.status + " " + result.statusText);  
      }  

There is an example that has always work for me.

Here is the complete article http://www.webdeveloperpost.com/Articles/How-to-use-jquery-ajax-in-asp-dot-net-web-page.aspx

It works well for those that want a straight forward way of using the jquery asp.net method call back

Jonjo
  • 21
  • 3